在 JavaScript 中转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11083254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:21:41  来源:igfitidea点击:

Casting to string in JavaScript

javascriptjquerystring

提问by gdoron is supporting Monica

I found three ways to cast a variable to Stringin 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:

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

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?

它们都产生相同的输出,但其中一个比其他的更好吗?
我会说它+ ""有一个优势,它可以节省一些角色,但这不是很大的优势,还有什么?

回答by Connell

They do behave differently when the valueis null.

valueis时,它们的行为确实不同null

  • null.toString()throws an error - Cannot call method 'toString' of null
  • String(null)returns - "null"
  • null + ""also returns - "null"
  • null.toString()抛出错误 -无法调用 null 的方法“toString”
  • String(null)返回 - “空”
  • null + ""也返回 - “空”

Very similar behaviour happens if valueis undefined(see jbabey's answer).

如果valueundefined(请参阅jbabey 的回答),则会发生非常相似的行为。

Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.

除此之外,性能差异可以忽略不计,除非您在巨大的循环中使用它们,否则不值得担心。

回答by jbabey

There are differences, but they are probably not relevant to your question. For example, the toString prototype does not exist on undefined variables, but you can cast undefined to a string using the other two methods:

存在差异,但它们可能与您的问题无关。例如,未定义变量上不存在 toString 原型,但您可以使用其他两种方法将 undefined 转换为字符串:

?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/

http://jsfiddle.net/f8YwA/

回答by Sarfraz

They behave the same but toStringalso provides a way to convert a number binary, octal, or hexadecimal strings:

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

Example:

例子:

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

回答by Simone C.

In addition to all the above, one should note that, for a defined value v:

除了上述所有内容外,还应注意,对于定义的值v

  • String(v)calls v.toString()
  • '' + vcalls v.valueOf()prior to any other type cast
  • String(v)电话 v.toString()
  • '' + vv.valueOf()在任何其他类型转换之前调用

So we could do something like:

所以我们可以这样做:

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

Tested in FF 34.0 and Node 0.10

在 FF 34.0 和 Node 0.10 中测试

回答by Sammy S.

According to this JSPerf test, they differ in speed. But unless you're going to use them in huge amounts, any of them should perform fine.

根据这个 JSPerf 测试,它们的速度不同。但除非你打算大量使用它们,否则它们中的任何一个都应该表现良好。

For completeness: As asawyeralready mentioned, you can also use the .toString()method.

为了完整性:正如asawyer已经提到的,您也可以使用该.toString()方法。

回答by jldec

if you are ok with null, undefined, NaN, 0, and false all casting to '' then (s ? s+'' : '')is faster.

如果您对 null、undefined、NaN、0 和 false 全部转换为 '' 没问题,那么(s ? s+'' : '')速度会更快。

see http://jsperf.com/cast-to-string/8

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

note - there are significant differences across browsers at this time.

注意 - 目前浏览器之间存在显着差异。

回答by Hyman

Real world example: I've got a log function that can be called with an arbitrary number of parameters: log("foo is {} and bar is {}", param1, param2). If a DEBUGflag is set to true, the brackets get replaced by the given parameters and the string is passed to console.log(msg). Parameters can and will be Strings, Numbers and whatever may be returned by JSON / AJAX calls, maybe even null.

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

  • arguments[i].toString()is not an option, because of possible nullvalues (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 JSPerfsays so.
  • arguments[i].toString()不是一个选项,因为可能的null值(见 Connell Watkins 回答)
  • JSLint 会抱怨arguments[i] + "". 这可能会也可能不会影响使用什么的决定。有些人严格遵守 JSLint。
  • 在某些浏览器中,连接空字符串比使用字符串函数或字符串构造函数要快一些(参见 Sammys S. answer 中的 JSPerf 测试)。在 Opera 12 和 Firefox 19 中,连接空字符串的速度快得可笑(在 Firefox 19 中为 95%)——或者至少JSPerf是这么说的。

回答by itinance

On this page you can test the performance of each method yourself :)

在此页面上,您可以自己测试每种方法的性能:)

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

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

here, on all machines and browsers, ' "" + str' is the fastest one, (String)str is the slowest

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