如何单独循环访问嵌套数组项



我有一个三维数组,例如:

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

我想对每个子数组中的第一项做一些事情,但对每个子数组中的第二项做其他事情。

因此,例如,我想找到array.lengtharray[0][0], array[1][0], array[2][0]之和等等。但是,我想要一个单独的结果array[0][1], array[1][1], array[2][1]等。

我仍在学习javascript(非常缓慢(,如果可能的话,我希望被指出正确的方向,而不是得到一个现成的解决方案。我一直在寻找可能的解决方案,我认为我可能需要一个嵌套的for循环,但我不确定如何构建它以获取所有值。

我一直在尝试类似的东西:

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

但我不明白发生了什么,不足以操纵结果。

如果有人能引导我朝着正确的方向寻找解决方案,那将不胜感激。

提前谢谢。

您可以考虑使用.reduce- 在每次迭代中,将第一个数组值添加到累加器的属性中,并对第二个数组值执行任何操作,将其结果分配给累加器的另一个属性。例如,假设对于第二项,您想获得他们的产品:

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);

在上面的代码中,累加器是一个具有两个属性的对象,sum(从 0 开始(和product(从 1 开始(。在reduce中,返回一个对象,新sum是旧sum加上数组中的第一项,新product是旧product乘以数组中的第二项。(当然,结果乘积为 0,因为在第一个子数组中,第二项为 0(

另请注意,数组始终需要用逗号分隔每个数组项 - 您需要修复输入数组的语法。

当然,如果有必要,你也可以for循环,但我认为数组方法更可取,因为它们功能更强大,具有更好的抽象,并且不需要手动迭代。带有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);

你只需要一个for循环,因为你只有一个数组,里面有数组,你知道你想要处理的索引。所以它将是这样的:

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);

首先,您发布的数组是 2D 数组而不是 3D 数组。

您发布的嵌套 for 循环非常适合您想要的内容。 您的第一个 for 语句正在循环遍历数组的第一个部分。第二个是获取第二个数组中的每个索引

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

我希望这对您的理解有所帮助

既然你要求帮助为你指出正确的方向,我建议你从简单的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);

你在第二行犯了一个错误。您需要遍历嵌套数组,然后从主数组中获取值。

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;
}
}
}

您可以使用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], ...
}

演示:

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

  • 在循环中使用调试器是观察和理解循环每个步骤的好方法

  • 使用 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 e.g 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 (e.g [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(i.e 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]]));

最新更新