gpt4 book ai didi

javascript - 考虑到行权重已知,如何对表行进行排序?

转载 作者:行者123 更新时间:2023-11-28 09:42:09 25 4
gpt4 key购买 nike

表:

<table>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>

表数据存在于数组中(请参阅table_matrics)。该数组已排序,并且 weight_index 跟踪顺序的变化(在本例中为 [1, 1, 1])。

var desc            = true;

var weight_index = [];

var table_matrics = [1, 2, 3];

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);

return weight;
});

如何使用weight_index对表行进行排序/重新渲染?

最佳答案

参见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 次操作/秒(12,300 次操作/300 毫秒),因此它比您的代码快一点。

编辑:

上面的代码可以简化(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 ),但我认为,随着行数的增加,性能会提高。

关于javascript - 考虑到行权重已知,如何对表行进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12239524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com