我注意到当针对负指数调用 toFixed
时,结果是一个数字,而不是一个字符串。
首先,让我们看一下规范。
Number.prototype.toFixed (fractionDigits)
Return a
String
containing this Number value represented in decimal fixed-point notation with fractionDigits digits after the decimal point. If fractionDigits isundefined
,0
is assumed.
实际发生的是(在 Chrome、Firefox、Node.js 中测试):
> -3e5.toFixed()
-300000
因此,返回值为-3e5
。另外,请注意这不是字符串。这是一个数字:
> x = -3e5.toFixed()
-300000
> typeof x
'number'
如果我将输入括在括号中,它会按预期工作:
> x = (-3e5).toFixed()
'-300000'
> typeof x
'string'
为什么会这样?什么解释?
最佳答案
我猜这是因为与符号运算符相比,成员 ('.') 运算符的优先级更高。
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
关于javascript - .toFixed() 调用负指数返回一个数字,而不是一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36722066/