JavaScript --->如何将字符串数组转换为数字数组?

时间:2018-03-12 15:02:54

标签: javascript

我的代码

  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 ]

2 个答案:

答案 0 :(得分:0)

强制返回值Number,替换

return tip;

一元加 +

return +tip;

Number构造函数

return Number(tip);

您可以将代码缩短为

var totals = bills.map( tip => +( tip + 15/100 ).toFixed( 2 ) ); 

答案 1 :(得分:-1)