我的代码
var bills = [50.23, 19.12, 34.01, 100.11, 12.15, 9.90,
29.11, 12.99,10.00, 99.22, 102.20, 100.10, 6.77, 2.22 ];
var totals = bills.map(function(tip){
tip += 15/100;
tip = tip.toFixed(2);
return tip;
});
console.log(totals);
返回
[ '50.38', '19.27', '34.16', '100.26', '12.30', '10.05',
'29.26', '13.14', '10.15', '99.37', '102.35', '100.25', '6.92', '2.37' ]
现在,如何将此字符串数组转换为数字数组
[ 50.38, 19.27, 34.16, 100.26, 12.30, 10.05,
29.26, 13.14, 10.15, 99.37, 102.35, 100.25, 6.92, 2.37 ]
答案 0 :(得分:0)
强制返回值到Number
,替换
return tip;
一元加 +
return +tip;
或 Number
构造函数
return Number(tip);
您可以将代码缩短为
var totals = bills.map( tip => +( tip + 15/100 ).toFixed( 2 ) );
答案 1 :(得分:-1)
您可以遍历数组并使用parseFloat()函数。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat