【问题标题】:How to get a list of html input values parsed to integers from a for loop?如何从 for 循环中获取解析为整数的 html 输入值列表?
【发布时间】:2019-09-21 19:02:11
【问题描述】:

我是 JavaScript 新手,正在编写一个采用 HTML 集合的程序 输入值并返回总和。

我想使用 for 循环将值的数据类型从字符串转换为整数,但是遇到了问题。

for (i = 0; i < allInp.length; ++i) {
var integer = [parseInt(allInp[i].value, 10)];
console.log(integer[i]);
}
// should return something like "3, 4, 5"

我希望 allInp 的值以整数形式返回,但以字符串形式返回。

【问题讨论】:

  • 什么是allInp?请也向我们展示那部分代码!还有....为什么要把integer 包装到一个数组中?
  • 您需要在循环之前创建一个result 数组,然后将其填充到循环中(每次迭代一个索引)。在循环内创建该数组文字没有帮助。

标签: javascript arrays for-loop parseint


【解决方案1】:

在循环外创建数组并使用push():

let allInp = document.querySelectorAll("input");

var arr = [];
for (i = 0; i < allInp.length; ++i) {
   arr.push(parseInt(allInp[i].value, 10));
}
console.log(arr);
<input type="text" value="2" />
<input type="text" value="1" />
<input type="text" value="7" />

【讨论】:

  • OP 想要一个列表,而不是一个总和?
猜你喜欢
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
相关资源
最近更新 更多