What's the best way to convert a number to a s

2019-01-01 12:22发布

What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?

Some examples:

  1. String(n)

  2. n.toString()

  3. ""+n

  4. n+""

20条回答
春风洒进眼中
2楼-- · 2019-01-01 12:40

Explicit conversions are very clear to someone that's new to the language. Using type coercion, as others have suggested, leads to ambiguity if a developer is not aware of the coercion rules. Ultimately developer time is more costly than CPU time, so I'd optimize for the former at the cost of the latter. That being said, in this case the difference is likely negligible, but if not I'm sure there are some decent JavaScript compressors that will optimize this sort of thing.

So, for the above reasons I'd go with: n.toString() or String(n). String(n) is probably a better choice because it won't fail if n is null or undefined.

查看更多
孤独寂梦人
3楼-- · 2019-01-01 12:40

The only valid solution for almost all possible existing and future cases (input is number, null, undefined, Symbol, anything else) is String(x). Do not use 3 ways for simple operation, basing on value type assumptions, like "here I convert definitely number to string and here definitely boolean to string".

Explanation:

String(x) handles nulls, undefined, Symbols, [anything] and calls .toString() for objects.

'' + x calls .valueOf() on x (casting to number), throws on Symbols, can provide implementation dependent results.

x.toString() throws on nulls and undefined.

Note: String(x) will still fail on prototype-less objects like Object.create(null).

If you don't like strings like 'Hello, undefined' or want to support prototype-less objects, use the following type conversion function:

/**
 * Safely casts any value to string. Null and undefined are converted to ''.
 * @param  {*} value
 * @return {string}
 */
function string (str) {
  return value == null ? '' : (typeof value === 'object' && !value.toString ? '[object]' : String(value));
}
查看更多
梦醉为红颜
4楼-- · 2019-01-01 12:41

I think it depends on the situation but anyway you can use the .toString() method as it is very clear to understand.

查看更多
低头抚发
5楼-- · 2019-01-01 12:44

In my opinion n.toString() takes the prize for its clarity, and I don't think it carries any extra overhead.

查看更多
临风纵饮
6楼-- · 2019-01-01 12:44

Other answers already covered other options, but I prefer this one:

s = `${n}`

Short, succinct, already used in many other places (if you're using a modern framework / ES version) so it's a safe bet any programmer will understand it.

Not that it (usually) matters much, but it also seems to be among the fastest compared to other methods.

查看更多
临风纵饮
7楼-- · 2019-01-01 12:48

You can call Number object and then call toString().

Number.call(null, n).toString()

You may use this trick for another javascript native objects.

查看更多
登录 后发表回答