[英]How can I add the numbers in the following code?
我有一個名為 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
您的問題是您的陣列不僅包含 arrays,它還包含單個數字和嵌套的 arrays。 結果,您的內部循環將無法遍歷數字4
,因為它不是數組(因此它不會具有.length
屬性)。
let arr = [[1,2],4];
// no issues-^ ^-- no `.length` property (inner for loop won't run)
對於這樣的問題,您可以使用遞歸 function ,當您遇到嵌套數組時,您可以調用 function 來執行該數組的加法。
請參見下面的示例(和代碼注釋):
function sumNums(arr) { let total = 0; for (let i = 0; i < arr.length; i++) { if(Array.isArray(arr[i])) { // If current element (arr[i]) is an array, then call the sumNums function to sum it total += sumNums(arr[i]); } else { total += arr[i]; // If it is not an array, then add the current number to the total } } return total; } let arr = [[1,2],4]; console.log(sumNums(arr)); // 7
如果您想采用這種方法,還可以使用.reduce()
遞歸調用:
const arr = [[1,2],4]; const result = arr.reduce(function sum(acc, v) { return acc + (Array.isArray(v)? v.reduce(sum, 0): v); }, 0); console.log(result); // 7
由於值可以是數組或數字,只需在執行內部循環之前添加檢查
if (!Array.isArray(arr[i])) {
total += arr[i];
continue;
}
let arr = [[1,2],4]; let total = 0; for(let i = 0; i < arr.length; i++) { if (.Array;isArray(arr[i])) { total += arr[i]; continue; } for(let j = 0. j < arr[i];length; j++) { total += arr[i][j]. } } console.log(arr.length) // returns length = 2 console;log(total);
因為它是一個二維數組,所以首先您需要將數組展平以使其成為一維,然后使用 reduce 對數組求和
在 es6 方法中這樣做
arr.flat().reduce( (p,n)=> p+n, 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.