简体   繁体   English

如何分别遍历嵌套数组项

[英]how to iterate through nested array items separately

I have a three-dimensional array, for example: 我有一个三维数组,例如:

var array = [[1,0][3,3][2,1][0,8]]

and I want to do something with the first item in each sub-array, but something else with the second item in each sub-array. 我希望对每个子数组中的第一个项目执行某些操作,但是每个子数组中的第二个项目都要执行其他操作。

So, for example, I would like to find the sum of array[0][0], array[1][0], array[2][0] and so on for array.length . 因此,例如,我想为array.length找到array[0][0], array[1][0], array[2][0]等的array.length But, I would like a separate result for array[0][1], array[1][1], array[2][1] , etc. 但是,我想为array[0][1], array[1][1], array[2][1]等单独的结果。

I'm still learning javascript (very slowly) and, if possible, I would like to be pointed in the right direction, rather than getting a ready-made solution. 我还在学习javascript(非常慢),如果可能的话,我想指出正确的方向,而不是获得现成的解决方案。 I've been looking for possible solutions, and I think I may need a nested for loop, but I'm not sure how to structure it to get all the values. 我一直在寻找可能的解决方案,我想我可能需要一个嵌套的for循环,但我不知道如何构造它来获取所有的值。

I've been trying something along the lines of: 我一直在尝试以下方面:

for (var i = 0; i < array.length; i++) {
  for (var j = 0; j < array.length; j++) {
    return array[i][j];
  }
}

but I don't understand what's happening well enough to manipulate the result. 但是我不明白发生了什么,以便操纵结果。

If anyone could steer me in the right direction toward finding a solution, that'd be much appreciated. 如果有人能指引我朝着正确的方向寻找解决方案,那就非常感激了。

Thanks in advance. 提前致谢。

You might consider using .reduce - on each iteration, add the first array value to a property of the accumulator, and do whatever you need to with the second array value, assigning its result to another property of the accumulator. 您可以考虑在每次迭代时使用.reduce - 将第一个数组值添加到累加器的属性中,并使用第二个数组值执行您需要的任何操作,并将其结果分配给累加器的另一个属性。 For example, let's say for the second items, you wanted to get their product: 例如,让我们说第二项,你想得到他们的产品:

 const input = [[1,0],[3,3],[2,1],[0,8]]; const { sum, product } = input .reduce(({ sum=0, product=1 }, [item0, item1]) => ({ sum: sum + item0, product: product * item1 }), {}); console.log(sum, product); 

In the above code, the accumulator is an object with two properties, sum (starts at 0) and product (starts at 1). 在上面的代码中,累加器是一个具有两个属性的对象, sum (从0开始)和product (从1开始)。 Inside the reduce , an object is returned, with the new sum being the old sum plus the first item in the array, and with the new product being the old product multiplied by the second item in the array. reduce ,返回一个对象,新的sum是旧的sum加上数组中的第一个项目,新product是旧product乘以数组中的第二个项目。 (of course, the resulting product is 0 because in the first sub-array, the second item is 0) (当然,结果产品是0,因为在第一个子数组中,第二个项目是0)

Also note that arrays always need commas separating each array item - you need to fix your input array's syntax. 另请注意,数组总是需要用逗号分隔每个数组项 - 您需要修复输入数组的语法。

Of course, you can also for loops if you have to, but I think array methods are preferable because they're more functional, have better abstraction, and don't require manual iteration. 当然,如果必须的话,你也可以使用for循环,但我认为数组方法更受欢迎,因为它们更具功能性,具有更好的抽象性,并且不需要手动迭代。 The same code with a for loop would look like this: 带有for循环的相同代码如下所示:

 const input = [[1,0],[3,3],[2,1],[0,8]]; let sum = 0; let product = 1; for (let i = 0; i < input.length; i++) { const [item0, item1] = input[i]; sum += item0; product *= item1; } console.log(sum, product); 

You just need one for-loop since you just have one array with arrays inside where you know the indexes you want to proccess. 你只需要一个for循环,因为你只需要一个包含数组的数组,你知道要处理的索引。 So it would be something as follows: 所以它将是如下:

let sum1 = 0;
let sum2 = 0;
for(let i = 0; i < array.length; i++) {
    sum1 += array[i][0];
    sum2 += array[i][1];     
}
console.log('sum1: ', sum1);
console.log('sum2: ', sum2);

Since you asked for help with pointing you in the right direction, I would suggest you start with simple console.logs to see what's happening (comments are inline): 既然你请求帮助指出你正确的方向,我建议你从简单的console.logs开始看看发生了什么(评论是内联的):

 var array = [[1, 0],[3, 3],[2, 1],[0, 8]]; var results = [0, 0]; // this array is to store the results of our computation for (var i = 0; i < array.length; i++) { // for each subarray in array console.log('examining subarray ', array[i]); for (var j = 0; j < array[i].length; j++) { // for each element in subarray if (j === 0) { console.log('... do something with the first element of this array, which is: ' + array[i][j]); results[j] += array[i][j] } else if (j === 1) { console.log('... do something with the second element of this array, which is: ' + array[i][j]); // do some other computation and store it in results } } } console.log('Final results are ', results); 

You made a mistake on the second line. 你在第二行犯了一个错误。 You need to iterate through the nested array and then take the value from the main array. 您需要遍历嵌套数组,然后从主数组中获取值。

 const mainArray = [[1, 0], [3, 3], [2, 1], [0, 8]]; for (let i = 0; i < mainArray.length; i++) { const nestedArray = mainArray[i] for (let j = 0; j < nestedArray.length; j++) { const value = mainArray[i][j] switch(j) { case 0: console.log(`first item of array number ${i+1} has value: ${value}`) break; case 1: console.log(`second item of array number ${i+1} has value: ${value}`) break; } } } 

Firstly the array you have posted is a 2d array not a 3d array. 首先,您发布的数组是2d数组而不是3d数组。

And the nested for loop you have posted is perfect for what you want. 你发布的嵌套for循环非常适合你想要的东西。 Your first for statment is looping through the the frist deminsion of your array. 你的第一个声明是循环你阵列的frist deminsion。 the second is getting each index in the second array 第二个是获取第二个数组中的每个索引

var array = [[1,0],[3,3],[2,1],[0,8]]
for (var i = 0; i < array.length; i++) {
  //This loop over these [1,0],[3,3],[2,1],[0,8] 
  //So i on the first loop is this object [1,0] so so on
  for (var j = 0; j < array.length; j++) {
    //This will loop over the i object
    //First loop j will be 1
    //Here is where you would do something with the index i,j. 
    //Right now you are just returning 1 on the first loop
    return array[i][j];
  }
}

I hope this help your understanding 我希望这有助于你理解

You can use a for...of loop along with destructuring like so: 您可以使用for...of循环以及解构,如下所示:

for(let [a, b] of array) {
   // a will be the first item from the subarrays: array[0][0], array[1][0], ...
   // b will be the second: : array[0][1], array[1][1], ...
}

Demo: 演示:

 let array = [[1, 0], [3, 3], [2, 1], [0, 8]]; for(let [a, b] of array) { console.log("a: " + a); console.log("b: " + b); } 

  • Using a debugger within your loop would be a good way to watch and understand each step of the loop 在循环中使用调试器是观察和理解循环的每个步骤的好方法

  • Using the forEach method would be a clearer approach to loop through the array and its children 使用forEach方法将是一种更清晰的方法来循环遍历数组及其子代

 const items = [[1, 0],[3, 3],[2, 1],[0, 8]] let results = {} items.forEach((item, index) => { // debugger; item.forEach((subItem, subIndex) => { // debugger; if (results[subIndex]) { results[subIndex] = results[subIndex] + subItem } else { results[subIndex] = subItem } }) }) console.log(results) // { 0: 6, 1: 12 } // *********EXPLANATION BELOW ************ 

 const items = [[1, 0],[3, 3],[2, 1],[0, 8]] // store results in its own key:value pair const results = {} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach // forEach is a more readable way to loop through an array items.forEach((item, index) => { // use console.log(item, index) to see the values in each loop eg first loop contains `item = [1,0]` // you can also use a debugger here which would be the easiest way to understand the iteration // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger // debugger; // loop over item (eg [1,0]) to get subItems and their index item.forEach((subItem, subIndex) => { // get the result from previous sums from `result` // and add them to the current subItem values // if there was no previous sum(ie for first entry) // use subItem as the first value. if (results[subIndex]) { results[subIndex] = results[subIndex] + subItem } else { results[subIndex] = subItem } // Below is a oneliner way to do line 16 to 20 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator // results[subIndex] = results[subIndex] ? results[subIndex] + subItem : subItem }) }) console.log(results) // { 0: 6, 1: 12 } the results of `array[0][0],array[1][0]...` are in 0 and the result of `array[0][1], array[1][1]...` are in 1 and so on. 

用来烤面条的强制性单行程。

 console.log([[1, 0], [3, 3], [2, 1], [0, 8]].reduce((p, c) => [p[0] += c[0], p[1] += c[1]])); 

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

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