两个数组相乘

时间:2019-09-09 19:14:51

标签: javascript arrays

我试图将两个相同长度的数组相乘,并从中创建第三个数组。

我已经尝试过循环,我认为嵌套循环将是前进的方向。

下面是我的尝试,它将整个数组相乘

var one = [1, 2, 3, 4, 5];
var two = [1, 2, 3, 4, 5];

//var partOne = one.length

var partOne = []
  for(var i=0; i<one.length;i++) {
    for(var j=0;j<two.length;j++) {
      partOne.push({value:one[i] * two[i]});
    }
  }

正在寻找与下面类似的内容;

var a = [3, 5]
var b = [5, 5]

//answer

var c = [15, 25]

2 个答案:

答案 0 :(得分:0)

let a = [3, 5];
let b = [5, 5];

// x is each element from a
// i is index of a
let c = a.map((x, i) => { return x * b[i]; });

返回

// Array [ 15, 25 ]

答案 1 :(得分:0)

subgroup

function multiply(a, b) {
    var c = [];
    for (var i=0; i<a.length;i++) {
        c.push(a[i]*b[i]);
    }
    return c;
}
var a = [3, 5 ];
var b = [5, 5 ];
var c = multiply(a, b);
console.log(c);