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?
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"] ]);
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]); }
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]);
}
}
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
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.