首页 > 解决方案 > 在javascript中将字符串拆分为单个数字

问题描述

以下代码使用动态类在表中搜索#operations每个:<td>".fuel "+ACID

let k = 0;  
let ac_fuel = 0;
parsed.data.forEach(arrayWithinData => {
    let ACID = parsed.data[k][0];
    if($("#operations td").hasClass("fuel "+ACID)) {
        console.log("we have a "+ACID);
        console.log(($("#operations td.fuel."+ACID).text()));
        ac_fuel += parseFloat($("#operations td.fuel."+ACID).html());
        console.log(ac_fuel);
    }
    k++;
})

ac_fuel 记录为一串数字,例如:

61.001.001.00643.00632.006.001.002181.22

我将如何拆分这些数字以便将它们加在一起?<td>期望的结果是类中每个元素的总和".fuel "+ACID

61.00 + 1.00 + 643.00 + 632.00 + 6.00 + 1.00 + 2181.22

标签: javascriptjquerystringsplitsum

解决方案


你应该使用 js .split 函数

let numsString = '61.001.001.00643.00632.006.001.002181.22';
let numsArr = numsString.split('.');
let summ = 0;

// set + before num, so it will be converted from string to num
numsArr.map(num => summ += +num);

console.log(summ);

所以在你的代码中,我相信这将是这样的

let k = 0;  
let ac_fuel = 0;
parsed.data.forEach(arrayWithinData => {
  let ACID = parsed.data[k][0];
  if($("#operations td").hasClass("fuel "+ACID)) {
    ac_fuel += parseFloat($("#operations td.fuel."+ACID).html());
  }
  k++;
})

let numsString = $("#operations td.fuel." + ACID).html();
let numsArr = numsString.split('.');
let summ = 0;

// set + before num, so it will be converted from string to num
numsArr.map(num => summ += +num);

ac_fuel += summ;
console.log(ac_fuel);

推荐阅读