简体   繁体   English

循环思想一个多维数组

[英]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] .您在这里所做的是遍历数组并仅获取索引 i 处的数组,例如arr[0][1,2] and (thirdInterval[i], thirdInterval[i+1]) is actually equals to ([1,2], [3,4])并且(thirdInterval[i], thirdInterval[i+1])实际上等于([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.您正在使用子数组迭代数组,这意味着thirdInterval[i]包含两个项目。 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]) .您可以使用索引thirdInterval[i][0]thirdInterval[i][1] ,但由于您使用这些值调用函数,因此您可以使用 spread 代替 - getNumbers(...thirdInterval[i])

In addition, the loop's condition should be i < thirdInterval.length if you don't want to skip the last item.另外,如果不想跳过最后一项,循环的条件应该是i < thirdInterval.length

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]) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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