Suppose you have a list of values that you want to store in a variable, and these values are stored in an array like this:
const array = [1, 2, 7, 24, 8];
let a = [];//initialize variable a here
You can iterate through the array using a loop to run a function on each value:
for (let i = 0; i < array.length; i++) {
setValue(array[i]);//call a function for each value
}
The function would look like this:
function setValue(val) {
a.push(val);
}
The output will be:
console.log(a);//output: [1, 2, 7, 24, 8]
If you want to add numbers from an input field, you can do it using jQuery:
<input type="number" id="my_input">
Here is the JavaScript code:
let a = [];//Declare a outside onchange function
//Onchange function to capture the new value whenever the input changes
$("#my_input").on("change", function() {
var input = $(this).val();//get new value from the input
setValue(parseFloat(input));//convert to number and call the setValue function
console.log(a);// output
});
The setValue function adds the new value to the array a:
function setValue(val) {
a.push(val);//adds new value to array a
}
See the demo here.