将数字转换为字符串的“最佳”方法是什么(从速度优势、清晰度优势、内存优势等方面考虑)?

一些例子:

字符串(n) n.toString() “”+n n+“”


当前回答

如果需要将结果格式化为特定的小数位数,例如表示货币,则需要类似toFixed()方法的东西。

number.toFixed( [digits] )

数字是小数点后要显示的位数。

其他回答

其他答案已经涵盖了其他选项,但我更喜欢这个:

s = `${n}`

简短,简洁,已经在许多其他地方使用过(如果您使用的是现代框架/ ES版本),所以任何程序员都能理解它。

这(通常)不是很重要,但与其他方法相比,它似乎也是最快的方法之一。

...JavaScript的解析器尝试进行解析 作为浮点字面值的数字上的点符号。

2..toString(); // the second point is correctly recognized
2 .toString(); // note the space left to the dot
(2).toString(); // 2 is evaluated first

只需使用模板文字语法:

`${this.num}`

对于数字字面值,访问属性的点必须与十进制点区分。如果你想在数字文字123上调用to String(),这留给你以下选项:

123..toString()
123 .toString() // space before the dot 123.0.toString()
(123).toString()

对于几乎所有可能的现有和未来情况(输入是number, null, undefined, Symbol,任何其他),唯一有效的解决方案是String(x)。不要使用3种方法进行简单的操作,基于值类型的假设,比如“这里我肯定将数字转换为字符串,这里肯定将布尔转换为字符串”。

解释:

String(x)处理空值,未定义,符号,[任何]和对象调用. tostring()。

+ x在x上调用. valueof()(转换为数字),在符号上抛出,可以提供依赖于实现的结果。

x.toString()抛出null和undefined。

注意:String(x)在没有原型的对象上仍然会失败,比如Object.create(null)。

如果你不喜欢'Hello, undefined'这样的字符串,或者想要支持无原型对象,请使用以下类型转换函数:

/**
 * 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));
}