问题
My goal for this is to be able to access properties of a nested array in a for loop, for example given the array.
[[1 , "one"],
[0.2 , "two"],
[0.3 , "three"]]
I'd like to be able to access index 0 over a loop.
My current way of doing this is:
function printArray() {
for (var i = arguments.length; i >= 0; i--) {
print(arguments[i][0]);
}
}
How ever this produces this error
Uncaught TypeError: Cannot read property '0' of undefined
When I expected
0.3
0.2
1
What is the correct way of looping over a nested array?
回答1:
There are a couple of ways to loop through an array.
Which one is the best?
It depends on what it's used for, and subjectivity.
Here's a few of them.
let arr = [[1 , "one"], [0.2 , "two"], [0.3 , "three"]];
// forEach loop
console.log('forEach loop');
arr.forEach((x, idx) => {
console.log(x[0]);
});
//for of loop
console.log('for-of loop');
for (elem of arr){
console.log(elem[0]);
}
//for in loop
console.log('for-in loop');
for (idx in arr){
console.log(arr[idx][0]);
}
// old-school for loop
console.log('for loop');
for (let i = 0; i < arr.length; i++) {
console.log(arr[i][0]);
}
// while loop
console.log('while loop');
let i = 0;
while (i < arr.length) {
console.log(arr[i][0]);
i++;
}
// do while loop
console.log('do while loop');
let j = 0;
do {
console.log(arr[j][0]);
j++;
} while (j < arr.length);
But about your function.
1) it's better to pass the array as a variable.
2) the last index of an array is it's length - 1
So if you want something that even works in older browsers.
To loop in ascending order of the index:
function printArray(arr) {
for (var i = 0; i < arr.length; i++) {
print(arr[i][0]);
}
}
To loop in descending order of the index:
function printArray(arr) {
for (var i = arr.length - 1; i >= 0; i--) {
print(arr[i][0]);
}
}
回答2:
Use for/of for iterables so you don't have to even worry about index dereferencing.
function printArray () {
for (const arg of [...arguments]) {
for (const nestedArg of arg) {
console.log(nestedArg);
}
}
};
printArray([
[1, "one"],
[0.2, "two"],
[0.3, "three"]
]);
回答3:
In the first iteration is i=3, that's past the array boundaries if used as index
let args = [
[1, "one"],
[0.2, "two"],
[0.3, "three"]
];
for (let i = args.length - 1; i >= 0; i--) {
console.log(args[i][0]);
}
回答4:
arguments is array of arguments pass to the function, in your case you should point to the first element of the argument array like this:
let data = [[1 , "one"],
[0.2 , "two"],
[0.3 , "three"]];
function printArray() {
for (var i = arguments[0].length -1 ; i >= 0; i--) {
console.log(arguments[0][i][0]);
}
}
printArray(data);
The error :
Uncaught TypeError: Cannot read property '0' of undefined
come form arguments.length, that will cause index out of bound array error
来源:https://stackoverflow.com/questions/60045889/how-to-use-nested-arrays-with-a-for-loop-in-javascript