为什么我的嵌套数组元素未正确添加到一起?

时间:2019-12-13 05:50:59

标签: javascript for-loop

Why I am getting this kinda error。但是当我计算它们的乘积时,它们看起来不错。

//The funtion will add all the values in that array....
function addArrayValues(arr) {
  var addition = 0;
  for (var i = 0; i < arr.length; i++) {
    for (var j = 0; j < arr[i].length; j++) {
      addition += arr[i][j];
    }
  }
  return addition;
}

var addition = addArrayValues([[[23], [34], [54]], [[34], [75]], [[75]], [65]]);
console.log(addition);

1 个答案:

答案 0 :(得分:2)

您没有数组数组-相反,您有一个数组数组 of 。您需要深入3个级别,而不仅仅是2个级别:

//The funtion will add all the values in that array....
function addArrayValues(arr){
    var addition=0;
    for(var i=0;i<arr.length;i++){
        for(var j=0;j<arr[i].length;j++){
            for (var k = 0; k < arr[i][j].length; k++) {
                addition+=arr[i][j][k];
            }
        }
    }
    return addition;
}

var addition=addArrayValues([[[23],[34],[54]],[[34],[75]],[[75]],[65]]);
console.log(addition);

或改用.flat

//The funtion will add all the values in that array....
const addArrayValues = arr => arr
    .flat(2)
    .reduce((a, b) => a + b, 0);

var addition=addArrayValues([[[23],[34],[54]],[[34],[75]],[[75]],[65]]);
console.log(addition);

您的原始代码首先隐式地将3深数组强制转换为字符串,例如,进行迭代

[[23],[34],[54]]

从计算开始

[23] + [34] + [54]

因此,在创建addition变量期间将数组转换为字符串。