简体   繁体   中英

Loop thought a multi dimensional array

I try to return a multidimensional array into a function to iterate it but I'm not sure what's wrong with my logic

const arr = [[1,2], [3,4],[5,6]]
for(let i = 0; i < thirdInterval.length-1; i++){
    getNumbers(thirdInterval[i], thirdInterval[i+1])
}

The result that I want to achieve is return the first element into the first argument of the function and the second element of the array into the second argument of the function.

What you are doing here is looping through the array and getting only the array at the index i, eg arr[0] which is [1,2] . and (thirdInterval[i], thirdInterval[i+1]) is actually equals to ([1,2], [3,4])

to access the first and second elements you should address them like the following:

for(let i = 0; i < thirdInterval.length-1; i++){
    getNumbers(thirdInterval[i][0], thirdInterval[i][1])
}
const arr = [[1,2][3,4][5,6]];

for (var i = 0; i < arr.length; i++;) {
    func(arr[i][0], arr[i][1];
}

You are iterating an array with sub-arrays, which means that thirdInterval[i] contains two items. You can get the items using the indexes thirdInterval[i][0] and thirdInterval[i][1] , but since you're calling a function with those values, you can use spread instead - getNumbers(...thirdInterval[i]) .

In addition, the loop's condition should be i < thirdInterval.length if you don't want to skip the last item.

Demo:

 const thirdInterval = [[1,2],[3,4],[5,6]] const getNumbers = console.log // mock getNumbers for (let i = 0; i < thirdInterval.length; i++) { getNumbers(...thirdInterval[i]) }

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