我是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的值以整数形式返回,但以字符串形式返回。
答案 0 :(得分:0)
在循环外创建数组并使用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" />