在JavaScript中转换为字符串 [英] Casting to string in JavaScript
问题描述
我发现在JavaScript中将变量转换为 String
的三种方法。
我在jQuery源代码中搜索了这三个选项,并且他们都在使用。
我想知道他们之间是否有任何差异:
I found three ways to cast a variable to String
in JavaScript.
I searched for those three options in the jQuery source code, and they are all in use.
I would like to know if there are any differences between them:
value.toString()
String(value)
value + ""
DEMO
它们都产生相同的输出,但其中一个比其他产品更好吗?
我会说 +
具有节省的优势一些角色,但那不是那么大的优势,还有其他什么?
They all produce the same output, but does one of them better than the others?
I would say the + ""
has an advantage that it saves some characters, but that's not that big advantage, anything else?
推荐答案
当值
<$ c $时,它们的行为会有所不同c> null 。
-
null.toString()
抛出错误 - 无法调用方法'toString'为null -
String(null)
返回 - null -
null +
也会返回 - null
null.toString()
throws an error - Cannot call method 'toString' of nullString(null)
returns - "null"null + ""
also returns - "null"
如果值
,则会发生非常类似的行为undefined
(参见 jbabey的回答)。
除此之外,性能差异可以忽略不计,除非你在巨大的循环中使用它们,否则不值得担心。
Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.
这篇关于在JavaScript中转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!