javascript - 在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
解决方案
你应该使用 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);
推荐阅读
- java - 在 android 的嵌套 Recyclerview 中显示数据
- xml - XSLT 匹配:正则表达式中字符 0 处的语法错误:量词之前没有表达式
- elasticsearch - 在弹性搜索中定义自定义标记器
- c# - 在 Winforms 应用程序中使用 System.Windows.Media API 会导致奇怪的 UI 行为
- python - Working with more than one datetime format in python
- metrics - YOLOv5 中指标的含义
- oracle - 在 oracle 中验证脚本
- javascript - 有没有办法选择与另一个相关的数组对象?
- ruby-on-rails - 如何在 Coffeescript 中导入 js 文件?
- javascript - Vue 3:在一个组件中制作其他道具的依赖道具