有没有办法在比较两个数组时获得更改的值?
我会更好地解释它。
让我说我有
arr1 = [1,2,3]
arr2 = [1,2,3]
arr2
动态创建,默认值与arr1
当我将arr2
更改为arr2 = [0,2,3]
时,如何检测更改后的值? (在这种情况下,1改为0)?
答案 0 :(得分:1)
这是一个简单的代码段,您可以像这样使用:
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;
}
}
答案 1 :(得分:1)
如果您只想知道哪个索引更改了哪个值,以及更改的值是什么,则可以使用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);
&#13;