如果我有一个数组A = [1, 4, 3, 2],B = [0, 2, 1, 2]我想返回一个带有值的新数组(A - B)[0, 2, 2, 0].在javascript中执行此操作的最有效方法是什么?
小智 23
ArrA.filter(n => !ArrB.includes(n));
Run Code Online (Sandbox Code Playgroud)
brk*_*brk 13
使用map方法map方法在其回调函数中有三个参数,如下所示
currentValue, index, array
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26477 次 |
| 最近记录: |