【问题标题】:Split string into individual numbers in javascript在javascript中将字符串拆分为单个数字
【发布时间】:2020-04-29 04:18:38
【问题描述】:

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

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

【问题讨论】:

  • 你能发布产生这个的 HTML 吗?
  • 在解析而不是追加时将它们推送到数组中,稍后再添加。
  • 不确定这怎么可能,因为您已经在使用ac_fuel += parseFloat(..)。您能否在此处使用jsfiddlesnippet 为此创建一个small demo 以显示正在发生的问题。
  • @CertainPerformance jsfiddle.net/q81wv65o

标签: javascript jquery string split sum


【解决方案1】:

你应该使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多