我正在尝试在 JavaScript 中访问多维数组中的元素。当我尝试使用变量访问数组内的数组中的元素时,结果是 undefined
。如果我使用数字而不是变量,我会得到结果..
let arr = [[1,2,3],[4,5,6],[7,8,9]];
for(let i=0; i < arr.length; i++) {
console.log(arr[i][arr.length]);
}
最佳答案
因为数组的长度是3,而你的最后一个数组索引是2。你可以修改它:
let arr = [[1,2,3],[4,5,6],[7,8,9]];
for(let i=0;i<arr.length;i++){
console.log(arr[i][arr.length - 1]); // Note the -1
}
这将返回3,6,9
关于javascript - 为什么当我尝试从 javascript 中的嵌套数组访问元素时,出现未定义的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823599/