见http://jsfiddle.net/rJe2U/1/
var desc = true,
weight_index = [],
table_matrics = [1, 2, 3],
tb=document.getElementById('tb'),
rowsCollection=tb.rows,
rows=[];
try{
rows=Array.prototype.slice.call(rowsCollection,0);
}catch(e){
for(var i=0,l=rowsCollection.length;i<l;i++){
rows.push(rowsCollection[i]);
}
}
table_matrics.sort(function(a, b){
var weight;
if(a == b){
weight = 0;
}else{
weight = (desc ? a > b : a < b) ? -1 : 1;
}
weight_index.push(weight);
if(weight>0){
tb.insertBefore(rows[b-1], rows[a-1])
}else if(weight<0){
tb.insertBefore(rows[a-1], rows[b-1])
}
return weight;
});
根据http://jsperf.com/sorting-table-rows-with-known-row-weight,性能约为 41,000 ops/秒(12,300 ops/300ms),因此它比您的代码快一点。
编辑:
上面的代码可以简化(http://jsfiddle.net/rJe2U/2/):
var desc = true,
weight_index = [],
table_matrics = [1, 2, 3],
tb=document.getElementById('tb'),
rows=[];
try{
rows=Array.prototype.slice.call(tb.rows,0);
}catch(e){
for(var i=0,rowsCollection=tb.rows,l=rowsCollection.length;i<l;i++){
rows.push(rowsCollection[i]);
}
}
table_matrics.sort(function(a, b){
var weight;
if(a == b){
weight = 0;
}else{
if(desc ? a > b : a < b){
weight=-1;
tb.insertBefore(rows[a-1], rows[b-1]);
}else{
weight=1;
tb.insertBefore(rows[b-1], rows[a-1]);
}
}
weight_index.push(weight);
return weight;
});
而且您不需要weight_index
,因此可以将其删除(http://jsfiddle.net/rJe2U/3/):
var desc = true,
table_matrics = [1, 2, 3],
tb=document.getElementById('tb'),
rows=[];
try{
rows=Array.prototype.slice.call(tb.rows,0);
}catch(e){
for(var i=0,rowsCollection=tb.rows,l=rowsCollection.length;i<l;i++){
rows.push(rowsCollection[i]);
}
}
table_matrics.sort(function(a, b){
var weight;
if(a == b){
return 0;
}
if(desc ? a > b : a < b){
tb.insertBefore(rows[a-1], rows[b-1]);
return -1;
}
tb.insertBefore(rows[b-1], rows[a-1]);
return 1;
});
性能似乎没有提高(http://jsperf.com/sorting-table-rows-with-known-row-weight/3),但我认为有大量的行它会。