问题描述
当我在十进制数字文字上调用toFixed()方法时,如下所示:
When I call the toFixed() method on a decimal number literal like so:
var a = 67.678.toFixed(2);
console.log(a);
结果有效并返回67.68
The result works and returns 67.68
但是,如果我在整数上调用方法 - 我收到错误
However if I call the method on an integer - I get an error
var b = 67.toFixed(2);
console.log(b); // causes ERROR
为什么会这样?
NB:
如果我将整数保存到变量 - toFixed()方法确实有效。
If I save the integer number to a variable - the toFixed() method does work.
var c = 67;
c = c.toFixed(2);
console.log(c); // returns 67.00
参见
引擎盖下发生了什么?
推荐答案
var b = 67.toFixed(2);
由于解析器无法推断,只需生成解析错误你的意思是它是一个数字文字后跟一个属性访问者(注意错误在第一行,而不是在 console.log(b)
)
var b = 67.toFixed(2);
Simply generates a parsing error as the parser can't deduce that you meant it to be a number literal followed by a property accessor (Notice that the error is on the first line, not on the console.log(b)
)
这对 67.678.toFixed(2)
起作用的原因是没有其他选择。解析器可以毫不含糊地推断出数字文字以8数字结束并且可以继续将下一个点解析为属性访问器(这导致首先装入 Number
对象BTW)。
The reason this works for 67.678.toFixed(2)
is that there's no other option. The parser can deduce without ambiguity that the number literal ended at the "8" digit and can continue parsing the next dot as a property accessor (which causes boxing into a Number
object first BTW).
解决方案显然很简单:
(67).toFixed(2);
这篇关于在数字文字上调用toFixed方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!