简体   繁体   English

添加两个数组并返回一个新数组

[英]Adding two arrays and returning a new array

Write a function addArrays that takes 2 arrays of numbers as parameters and returns a new array where elements at same index position are added together. 编写一个addArrays函数,该函数将2个数字数组作为参数,并返回一个新数组,其中将相同索引位置的元素加在一起。 For example: addArrays([1,2,3], [4,3,2,1]); 例如:addArrays([1,2,3],[4,3,2,1]); // => [5,5,5,1] // => [5,5,5,1]

I am trying to use nested for loops but its giving an incorrect answers.... 我正在尝试使用嵌套的for循环,但给出的答案不正确。

  function addArrays(num1, num2){
      var result = [];
      for(var i=0; i< num1.length; i++){
        for(var j=0; j<num2.length; j++){
          result.push(num1[i] + num2[j]);
      }
      }
      return result;
    }

I suggest to use only one loop with a check of the length and some default values if the elements do not exists. 我建议仅使用一个循环检查长度,如果元素不存在,则使用一些默认值。

 function addArrays(array1, array2) { var i, l = Math.max(array1.length, array2.length), result = []; for (i = 0 ; i < l; i++) { result.push((array1[i] || 0) + (array2[i] || 0)); } return result; } console.log(addArrays([1, 2, 3], [4, 3, 2, 1])); 

There is no need to nest with 2 loops. 无需嵌套2个循环。 Nested loops for arrays are used if you have a 2 dimensional array. 如果您有二维数组,则使用数组的嵌套循环。

function addArrays(num1, num2){
    var result = [];
    var size = Math.max(num1.length, num2.length);

    for(var i = 0; i < size; i++){
        result.push(num1[i] + (num2[i]);

    }
    return result;
}

You can also default it to 0 if the arrays are different lengths and you go off the end like this 如果数组的长度不同并且像这样结束,也可以将其默认设置为0

(num1[i] || 0) + (num2[i] || 0)

This chooses either the number in the array, or 0 if it doesnt exist 这将选择数组中的数字,如果不存在则选择0

function addArrays(num1, num2){
      var result = [];
      for(var i=0; i< num1.length; i++){
          result.push(num1[i] + num2[i]);
      }
      return result;
}

For those a little more progressive in nature... 对于那些本质上有点进步的人...

let a = [1, 2, 3], b = [4, 3, 2, 1], l = Math.max(a.length, b.length)
const addArrays = ((a[l-1]) ? a : b).map((v, k) => (a[k] || 0) + (b[k] || 0))

console.log(addArrays) // [ 5, 5, 5, 1 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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