gpt4 book ai didi

Javascript 按数据值最高优先排序 div

转载 作者:行者123 更新时间:2023-11-30 08:27:02 25 4
gpt4 key购买 nike

我有这个代码。如果您查看数据,id 就是 div 的 id。接下来是 hovers 字段,每个字段都有一个数值。

每次悬停 div 时,下面的代码都会增加悬停。

var counter = [
{id: 1, hovers: 1},
{id: 2, hovers: 0},
{id: 3, hovers: 8},
{id: 4, hovers: 5},
{id: 5, hovers: 3},
{id: 6, hovers: 4},
{id: 7, hovers: 2},
{id: 8, hovers: 9},
{id: 9, hovers: 2}
]

$('div').mouseover(function() {
var obj = counter.find(e => e.id == $(this).attr('id'))
if(obj) obj.hovers++
console.log(obj)
})

这是悬停和计数器的 html div。

<div id="1"><p>Box 1</p></div>
<div id="2"><p>Box 2</p></div>
<div id="3"><p>Box 3</p></div>
<div id="4"><p>Box 4</p></div>
<div id="5"><p>Box 5</p></div>
<div id="6"><p>Box 6</p></div>
<div id="7"><p>Box 7</p></div>
<div id="8"><p>Box 8</p></div>
<div id="9"><p>Box 9</p></div>

如果我们查看计数器数据。

我怎样才能移动 div,使悬停次数最多的 div 排在第一位,并与其他 div 以该顺序排列?

最佳答案

所以您尝试做的事情实际上非常昂贵。使用您当前的数据结构,您必须对 counter 进行排序每次发生鼠标悬停时数组以保持正确的顺序。这意味着,如果你有 N鼠标悬停和 M counter 中的项目,此操作的时间复杂度为 O(N*MlogM) .

还有每次悬停时搜索数组的性能命中。

假设您需要此排序列表的频率远低于悬停次数,您可以在需要时进行排序,而不是每次悬停时进行排序。

此外,您可以将数据保存在 Map<id, hoverCount> 中而不是数组,使悬停更新成为恒定时间操作。这也将允许使用任何 JS 值作为 id 而不仅仅是数字。

const counter = new Map([
[1, 1],
[2, 0],
[3, 8],
[4, 5],
[5, 3],
[6, 4],
[7, 2],
[8, 9],
[9, 2]
]);

$('div').mouseover(function() {
const id = Number($(this).attr('id'));
if (counter.has(id)) {
counter.set(id, counter.get(id) + 1);
}
});

如果您知道您的 id 将匹配索引值 - 每个元素都为 1,就像现在一样,那么就不需要 map 也不需要遍历数组,只需立即使用 id 作为索引访问:

$('div').mouseover(function() {
const idx = Number($(this).attr('id')) - 1;
if (idx >= 0 && idx < counter.length) {
counter[idx].hovers += 1;
}
});

就排序而言,这只是比较 hovers 的问题每个元素的属性:

// sorting the Map
getSorted() {
return [...counter.entries()].sort((a, b) => b[1] - a[1]);
}

// sorting the array of <id, hovers> objects
getSorted() {
return counter.sort((a, b) => b.hovers - a.hovers));
}

关于Javascript 按数据值最高优先排序 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43946615/

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