不复制数据,因为字符串和并行数组会这样做。
function chkOrder(a) {
for(var i =1; i< a.length; i++)
if (a[i-1] > a[i]) return false;
return true;
}
如果您颠倒顺序,您可能需要处理 th ">" 符号,这也将在第一次出现时返回 false(未排序)
如果我们可以控制包含的对象,那么我们就可以控制对象的变化并触发父排序
function O(parent,data) {//initialize with parent and value array/object
this.parent=parent;
this.data=data;
//shortcurt to sort parent
this.sort=function()
{console.log("sortingparent");this.parent.sort(this.parent.sortfunc);}
this.setData=function(data) {
this.data=data;
this.sort();
}
//if changes can be groupped then is more efficient to signal parent dirty and sort latter
this.setKey=function(key,value) {//change value in the data
if (key==parent.sortkey&&value!=this.data[key]) {
this.data[key]=value;
this.sort();
} else this.data[key]=value;
}
this.parent.push(this);
this.sort();
return this;
}
//-------
//using a simple array, this could also be and object and have specific func's
var arr=[];
//example, sort by name, ascending
arr.sortkey="name";
//closure to build a sort predicate bound to the used key
function setkey(key) {return function(a,b) {return a.data[key]>b.data[key];}}
arr.sortfunc=setkey(arr.sortkey);
var b=new O(arr,{name:"B",value:0});
var c=new O(arr,{name:"C",value:2});
var a=new O(arr,{name:"A",value:1});
var d=new O(arr,{name:"D",value:3});
console.log("changing value");
a.setKey("value",100);//when not sorting by value its the same as a.data.value=100
console.log("changing name");
a.setKey("name","X");//this will fire parent sort
for(n=0;n<arr.length;n++) console.log(arr[n].data.name,"=",arr[n].data.value);