我找到了三种在JavaScript中将变量转换为String的方法。 我在jQuery源代码中搜索了这三个选项,它们都在使用中。 我想知道它们之间有什么区别:

value.toString()
String(value)
value + ""

DEMO

它们都产生相同的输出,但其中一个比其他的更好吗? 我会说+ ""有一个优势,它节省了一些字符,但这不是那么大的优势,还有吗?


当前回答

真实世界的例子:我有一个日志函数,可以用任意数量的参数调用:log(“foo是{},bar是{}”,param1, param2)。如果DEBUG标志被设置为true,括号将被给定的参数替换,字符串将被传递给console.log(msg)。参数可以是字符串,数字和JSON / AJAX调用返回的任何东西,甚至可能是null。

arguments[i].toString() is not an option, because of possible null values (see Connell Watkins answer) JSLint will complain about arguments[i] + "". This may or may not influence a decision on what to use. Some folks strictly adhere to JSLint. In some browsers, concatenating empty strings is a little faster than using string function or string constructor (see JSPerf test in Sammys S. answer). In Opera 12 and Firefox 19, concatenating empty strings is rediculously faster (95% in Firefox 19) - or at least JSPerf says so.

其他回答

在这个页面上,你可以自己测试每个方法的性能:)

http://jsperf.com/cast-to-string/2

这里,在所有机器和浏览器上,' "" + str '是最快的,(String)str是最慢的

有不同之处,但它们可能与你的问题无关。例如,未定义变量上不存在toString原型,但是你可以使用其他两个方法将未定义转换为字符串:

​var foo;

​var myString1 = String(foo); // "undefined" as a string

var myString2 = foo + ''; // "undefined" as a string

var myString3 = foo.toString(); // throws an exception

http://jsfiddle.net/f8YwA/

真实世界的例子:我有一个日志函数,可以用任意数量的参数调用:log(“foo是{},bar是{}”,param1, param2)。如果DEBUG标志被设置为true,括号将被给定的参数替换,字符串将被传递给console.log(msg)。参数可以是字符串,数字和JSON / AJAX调用返回的任何东西,甚至可能是null。

arguments[i].toString() is not an option, because of possible null values (see Connell Watkins answer) JSLint will complain about arguments[i] + "". This may or may not influence a decision on what to use. Some folks strictly adhere to JSLint. In some browsers, concatenating empty strings is a little faster than using string function or string constructor (see JSPerf test in Sammys S. answer). In Opera 12 and Firefox 19, concatenating empty strings is rediculously faster (95% in Firefox 19) - or at least JSPerf says so.

除了以上所有的,我们应该注意到,对于一个定义值v:

调用v. tostring () + v在任何其他类型强制转换之前调用v.valueOf()

所以我们可以这样做:

var mixin = {
  valueOf:  function () { return false },
  toString: function () { return 'true' }
};
mixin === false;  // false
mixin == false;    // true
'' + mixin;       // "false"
String(mixin)     // "true"

在FF 34.0和Node 0.10中测试

它们的行为相同,但toString也提供了一种转换数字二进制,八进制或十六进制字符串的方法:

例子:

var a = (50274).toString(16)  // "c462"
var b = (76).toString(8)      // "114"
var c = (7623).toString(36)   // "5vr"
var d = (100).toString(2)     // "1100100"