I am new to JavaScript & writing a program that takes a collection of HTML input values and returning the sum.
I want to convert the data-type of the value from string to integer with a for loop, but am having issues.
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"
I expect the values of allInp to be returned as integers but returns them as strings.
Create the array outside the loop and use 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" />