【问题标题】:How can I add the numbers in the following code?如何在以下代码中添加数字?
【发布时间】: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


【解决方案1】:

您的问题是您的数组不仅包含数组,还包含单个数字和嵌套数组。因此,您的内部循环将无法遍历数字 4,因为它不是数组(因此它不会有 .length 属性)。

let arr = [[1,2],4];
// no issues-^   ^-- no `.length` property  (inner for loop won't run)

对于这样的问题,您可以使用recursive function,当您遇到嵌套数组时,您可以调用您的函数来执行该数组的加法。

参见下面的示例(和代码 cmets):

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

【讨论】:

    【解决方案2】:

    由于值可以是数组或数字,只需在执行内部循环之前添加检查

       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);

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 1970-01-01
      • 2021-10-31
      • 2018-12-19
      • 2019-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多