0

toFixed(2)为什么我在执行下面的价格数组的 console.log 时无法使用?为什么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] 
4

1 回答 1

4

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)));

于 2018-02-26T07:54:16.477 回答