如何在javascript中从另一个数组中减去一个数组

时间:2017-07-27 05:35:45

标签: javascript

如果我有一个数组A = [1, 4, 3, 2]B = [0, 2, 1, 2]我想返回一个值为[0, 2, 2, 0]的新数组(A - B)。在javascript中执行此操作的最有效方法是什么?

4 个答案:

答案 0 :(得分:13)

ArrA.filter(n => !ArrB.includes(n));

答案 1 :(得分:11)

使用map方法 map方法在其回调函数中有三个参数,如下所示

currentValue, index, array



var a = [1, 4, 3, 2],
  b = [0, 2, 1, 2]

var x = a.map(function(item, index) {
  // In this case item correspond to currentValue of array a, 
  // using index to get value from array b
  return item - b[index];
})
console.log(x);




答案 2 :(得分:2)

For简单有效。

点击此处:JsPref - For Vs Map Vs forEach



var a = [1, 4, 3, 2],
  b = [0, 2, 1, 2],
  x = [];

for(var i = 0;i<=b.length-1;i++)
  x.push(a[i] - b[i]);
  
console.log(x);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

如果要覆盖第一个表中的值,只需对数组forEach使用forEach方法即可。 ForEach方法采用与map方法(element,index,array)相同的参数。它与之前使用map关键字的答案类似,但这里我们没有返回值,而是自己分配值。

&#13;
&#13;
var a = [1, 4, 3, 2],
  b = [0, 2, 1, 2]
  
a.forEach(function(item, index, arr) {
  // item - current value in the loop
  // index - index for this value in the array
  // arr - reference to analyzed array  
  arr[index] = item - b[index];
})

//in this case we override values in first array
console.log(a);
&#13;
&#13;
&#13;

相关问题