簡體   English   中英

數組和JavaScript-如何比較兩個數組

[英]Array and javascript - how to compare two arrays

比較兩個數組時,是否有辦法獲取更改的值?

我會更好地解釋。

假設我有

arr1 = [1,2,3]
arr2 = [1,2,3]

動態創建arr2 ,默認值與arr1相同

當我將arr2更改為arr2 = [0,2,3]如何檢測已更改的值? (在這種情況下,將1更改為0)?

這是一個簡單的代碼片段,您可以像這樣使用:

1)首先用ArrayObserver包裝您的數組

2)然后只需使用update方法來分配新的數組值

3)跟蹤onUpdated回調中的新元素

4)在aObserver.array訪問您的數組

讓我知道代碼對您是否有意義以及我們是否需要更改某些內容

 var array = [10, 15]; var aObserver = new ArrayObserver(array); aObserver.onUpdated(function(newValues, oldArray){ console.log('New values are:'); console.log(newValues); }); /* use the update method to assing new value of the array */ aObserver.update([10, 12]); aObserver.update([15, 12]); console.log('array values is'); console.log(aObserver.array); /* Simple class that is holding the array and when array is updated through this class it will give you the new values in a callback of onUpdated method */ function ArrayObserver(array){ var that = this; var callback = null; that.array = array; that.update = function(newArray){ var newValues = []; /* get a copy of the old array */ var oldValues = that.array.slice(); for(var i = 0; i < newArray.length; i++){ if(!~that.array.indexOf(newArray[i])){ /* this is a new value */ newValues.push(newArray[i]); } } if(callback && {}.toString.call(callback) === '[object Function]'){ callback(newValues, oldValues); } that.array = newArray; } that.onUpdated = function(cb){ callback = cb; } } 

如果只想知道哪個索引更改了哪個值,什么是更改的值,可以使用Array#reduce創建更改數組。

 var arr1 = [1, 2, 3]; var arr2 = [0, 2, 3]; function whatChanged(arr1, arr2) { return arr2.reduce(function(d, v, i) { v !== arr1[i] && d.push({ index: i, from: arr1[i], to: v }); return d; }, []); } var diff = whatChanged(arr1, arr2); console.log(diff); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM