在JavaScript中转换为字符串 [英] Casting to string in JavaScript

查看:140
本文介绍了在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

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 null
  • String(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆