我使用比较两个数组的标准方法,但它就像做标准 O(n^2) 一样慢你们能看到问题吗?
diffArray: function (arr1, arr2, observableArray, mapping) {
//We cant sort orginal arrays
var o = arr1.slice(0);
var n = arr2.slice(0);
// sort both arrays (or this won't work)
var sorter = function (left, right) {
return mapping.key(left) - mapping.key(right);
};
o.sort(sorter); n.sort(sorter);
// declare temporary variables
var op = 0; var np = 0;
var added = []; var removed = [];
// compare arrays and add to add or remove lists
while (op < o.length && np < n.length) {
if (mapping.key(o[op]) < mapping.key(n[np])) {
// push to diff?
removed.push(o[op]);
op++;
}
else if (mapping.key(o[op]) > mapping.key(n[np])) {
// push to diff?
added.push(n[np]);
np++;
}
else {
this.diffMembers(o[op], n[np]);
op++; np++;
}
}
// add remaining items
if (np < n.length)
added = added.concat(n.slice(np, n.length));
if (op < o.length)
removed = removed.concat(o.slice(op, o.length));
ko.utils.arrayForEach(removed, function (item) {
this.itemDeleted(item, mapping);
}.bind(this));
ko.utils.arrayForEach(added, function (item) {
if (observableArray.concurrencyExtendOptions) {
this.itemAdded(observableArray, item, mapping);
}
} .bind(this));
}
注意:映射对象只是用户提供的用于比较数组中对象的辅助对象,arr1 和 arr2 是标准 JS 数组,而 observableArray 是未包装的 Knockout 数组
它基于 C# 代码示例,所以也许 JS 中的排序算法不是那么好?