最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What is the shortest way of converting any JavaScript value to a string? - Stack Overflow

programmeradmin3浏览0评论

I have a function, say:

setValue: function(myValue) {
  ...
}

The caller might pass a string, number, boolean, or object. I need to ensure that the value passed further down the line is a string. What is the safest way of doing this? I realize there are many ways some types (e.g. Date) could be converted to strings, but I am just looking for something reasonable out of the box.

I could write a series of typeof statements:

if (typeof myValue == "boolean") {}
else if () {}
...

But that can be error-prone as types can be missed.

Firefox seems to support writing things like:

var foo = 10; foo.toString()

But is this going to work with all web browsers? I need to support IE 6 and up.

In short, what is the shortest way of doing the conversion while covering every single type?

-Erik

I have a function, say:

setValue: function(myValue) {
  ...
}

The caller might pass a string, number, boolean, or object. I need to ensure that the value passed further down the line is a string. What is the safest way of doing this? I realize there are many ways some types (e.g. Date) could be converted to strings, but I am just looking for something reasonable out of the box.

I could write a series of typeof statements:

if (typeof myValue == "boolean") {}
else if () {}
...

But that can be error-prone as types can be missed.

Firefox seems to support writing things like:

var foo = 10; foo.toString()

But is this going to work with all web browsers? I need to support IE 6 and up.

In short, what is the shortest way of doing the conversion while covering every single type?

-Erik

Share Improve this question asked May 26, 2009 at 18:05 ebruchezebruchez 7,8576 gold badges31 silver badges41 bronze badges 1
  • 2 This subject has already been discussed : stackoverflow./questions/869773/… – Fabien Ménager Commented May 26, 2009 at 18:13
Add a ment  | 

5 Answers 5

Reset to default 9
var stringValue = String(foo);

or even shorter

var stringValue = "" + foo;
value += '';

If you use myValue as a string, Javascript will implicity convert it to a string. If you need to hint to the Javascript engine that you're dealing with a string (for example, to use the + operator), you can safely use toString in IE6 and up.

what about forcing string context, e.g. ""+foo?

Yet another way is this:

var stringValue = (value).toString();
发布评论

评论列表(0)

  1. 暂无评论