简体   繁体   中英

How to get the output value of for loop in an array in javascript

Hi i am getting the values from a dynamically created input form with following loop.

i need to store the for loop out put value to be stored in an array like below

points= [[0,420],[10,373],[20,340],[30,313],[40,293],[50,273],[60,259],[70,243]]

my for loop code

//for example intId = 4
for(i=0;i<intId;i++){
        var it=i+1
        var af = $('#af'+it).val()
        var sp = $('#sp'+it).val()
        var ad = [af,sp]
        console.log(ad);
    }

i need the result in this format as mentioned above for eg.

[[af1,sp1],[af2,sp2],[af3,sp3],...]

You can create an array and store the values in the array.

const arr = [] // Initialize an empty array
for(i=0;i<intId;i++){
    var it = i+1
    var af = $('#af'+it).val()
    var sp = $('#sp'+it).val()
    var ad = [af,sp]
    arr.push(ad); // Append to array
}
console.log(arr)

Unless I'm missing something exceptionally obvious here, all you need to do is create an array, and then .push the new arrays into it...

var newArray = [];
for (i=0;i<intId;i++){
    var it=i+1
    var af = $('#af'+it).val()
    var sp = $('#sp'+it).val()
    var ad = [af,sp]
    newArray.push(ad);
}
console.log(newArray);

As per the comment by the OP...

i need the output like this [2, 3] [1, 2] but i am getting like this ["2", "3"] ["1", "2"]

Then use parseInt to get the actual number...

var newArray = [];
for (i=0;i<intId;i++){
    var it=i+1
    var af = parseInt($('#af'+it).val())
    var sp = parseInt($('#sp'+it).val())
    var ad = [af,sp]
    newArray.push(ad);
}
console.log(newArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM