Javascript - Sum two arrays in single iteration

后端 未结 13 2000
我寻月下人不归
我寻月下人不归 2020-11-29 05:56

I want to sum each value of an array of numbers with its corresponding value in a different array of numbers, and I want to do this without looping through each individual v

相关标签:
13条回答
  • 2020-11-29 06:35

    In ES6+, you can use arrow function to make the code clear:

    var x = [1,2,3];
    var y = [2,3,4];
    var sum = x.map( (val, i) => val + y[i] );
    
    console.log(sum); //Array [3, 5, 7]
    
    
    var z = [3,4,5];
    var add3 = x.map( (val, i) => val + y[i] + z[i] );
    
    console.log(add3); //Array [6, 9, 12]
    
    0 讨论(0)
提交回复
热议问题