toFixed() 不适用于数组
toFixed() not working well with an array
为什么我在对下面的价格数组执行 console.log 时无法使用 toFixed(2)
?为什么 toFixed
在这种情况下不起作用?
我收到以下错误:Error: VM1105:8 Uncaught TypeError: prices.toFixed is not a function at <anonymous>:8:20
这是简单的代码:
var prices = [1.23, 48.11, 90.11, 8.50, 9.99, 1.00, 1.10, 67.00];
// your code goes here
prices[0]= 1.99;
prices[2]= 99.99;
prices[6]= 1.95;
console.log(prices.toFixed(2));
当我刚打印出来时console.log(prices);
我得到以下内容,实际数组中缺少小数点。为什么会这样以及如何补救?
(8) [1.99, 48.11, 99.99, 8.5, 9.99, 1, 1.95, 67]
Number#toFixed
是 Number
的方法,而不是 Array
的方法。您需要映射所有值并对其应用 toFixed
。
var prices = [1.23, 48.11, 90.11, 8.50, 9.99, 1.00, 1.10, 67.00];
prices[0]= 1.99;
prices[2]= 99.99;
prices[6]= 1.95;
console.log(prices.map(v => v.toFixed(2)));
为什么我在对下面的价格数组执行 console.log 时无法使用 toFixed(2)
?为什么 toFixed
在这种情况下不起作用?
我收到以下错误:Error: VM1105:8 Uncaught TypeError: prices.toFixed is not a function at <anonymous>:8:20
这是简单的代码:
var prices = [1.23, 48.11, 90.11, 8.50, 9.99, 1.00, 1.10, 67.00];
// your code goes here
prices[0]= 1.99;
prices[2]= 99.99;
prices[6]= 1.95;
console.log(prices.toFixed(2));
当我刚打印出来时console.log(prices); 我得到以下内容,实际数组中缺少小数点。为什么会这样以及如何补救?
(8) [1.99, 48.11, 99.99, 8.5, 9.99, 1, 1.95, 67]
Number#toFixed
是 Number
的方法,而不是 Array
的方法。您需要映射所有值并对其应用 toFixed
。
var prices = [1.23, 48.11, 90.11, 8.50, 9.99, 1.00, 1.10, 67.00];
prices[0]= 1.99;
prices[2]= 99.99;
prices[6]= 1.95;
console.log(prices.map(v => v.toFixed(2)));