【发布时间】:2021-03-30 21:28:34
【问题描述】:
我有一个名为 arr = [[1,2],4] 的数组,以及用于访问数字的 for 循环。但我似乎无法添加最后一个数字。为什么它不起作用?
let arr = [[1,2],4];
let total = 0;
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < arr[i].length; j++) {
total += arr[i][j];
}
}
console.log(arr.length) // returns length = 2
console.log(total); // returns total = 3
【问题讨论】:
-
因为
4不是数组。所以你不能循环它。要么您将结构更新为[ [ 1,2 ], [ 4 ] ],要么更新算法 -
那是因为内部循环试图读取数字 4 的长度,这是未定义的
标签: javascript arrays function if-statement multidimensional-array