2017-07-27 57 views
-2

如果我有一個數組A = [1, 4, 3, 2]B = [0, 2, 1, 2]我想返回一個新數組(A - B),其值爲[0, 2, 2, 0]。什麼是最有效的方法來做到這一點的JavaScript?如何從javascript中減去另一個陣列

+4

的可能的複製[什麼是計算使用Javascript陣列設定的差最快或最優雅的方式?(https://stackoverflow.com/questions/1723168/what-is - 最快或最優雅的方式計算一個集差異使用javasc) – jhpratt

+0

你的代表的用戶應該知道共享努力的重要性。 SO是爲你的問題得到幫助,而不是你的要求的解決方案 – Rajesh

+0

試試這個, https://stackoverflow.com/questions/1187518/javascript-array-difference – ImAnand

回答

7

使用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);

0

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);

+0

這兩個數組的長度,假設是相同的。否則會造成問題。或者之前處理它。 –

+0

@AvneshShakya是的。這兩個陣列應該是相同的,這就是問題所在。 – Sankar

0

如果你想在第一個表重寫值,你可以簡單地使用數組forEach的forEach方法。 ForEach方法使用與map方法(element,index,array)相同的參數。它與之前用map關鍵詞的答案類似,但這裏我們沒有返回值,而是由自己分配值。

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);