繁体   English   中英

如何在以下代码中添加数字?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM