简体   繁体   中英

Split string into individual numbers in javascript

The following code searches the table #operations for every <td> with the dynamic class ".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 is logged as a string of numbers eg:

61.001.001.00643.00632.006.001.002181.22

How would I split these numbers up so I can add them together? the desired result is the sum of every <td> element with the class ".fuel "+ACID :

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

You should use js.split function

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

So in your code I believe this will be something like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM