如何在JavaScript中使用带有for循环的嵌套数组 [英] How to use nested arrays with a for loop in javascript
问题描述
我的目标是能够在for循环中访问嵌套数组的属性,例如给定数组.
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"]]
我希望能够通过循环访问索引0.
I'd like to be able to access index 0 over a loop.
我目前的做法是:
function printArray() {
for (var i = arguments.length; i >= 0; i--) {
print(arguments[i][0]);
}
}
这怎么会产生此错误
Uncaught TypeError: Cannot read property '0' of undefined
当我期望
0.3
0.2
1
循环遍历嵌套数组的正确方法是什么?
What is the correct way of looping over a nested array?
推荐答案
有两种方法可以遍历数组.
There are a couple of ways to loop through an array.
哪个是最好的?
这取决于它的用途和主观性.
It depends on what it's used for, and subjectivity.
这里有几个.
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);
但是关于您的功能.
1)最好将数组作为变量传递.
2)数组的最后一个索引是它的长度-1
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.
以索引的升序循环:
function printArray(arr) {
for (var i = 0; i < arr.length; i++) {
print(arr[i][0]);
}
}
以索引的降序循环:
function printArray(arr) {
for (var i = arr.length - 1; i >= 0; i--) {
print(arr[i][0]);
}
}
这篇关于如何在JavaScript中使用带有for循环的嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!