gpt4 book ai didi

javascript - 为什么这个循环会逐渐变慢?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:13:01 24 4
gpt4 key购买 nike

for (i = 0; i < $('body > p font i').length; i++) {
current = [$('body > p font i').eq(index), $('body > p font i').eq(index).index('body > p font u, body > p font i')];
getState(current[1]);
}

function getState(index) {
// Lookup the object's index, then crawl up until you find a match
while ($('body > p font u, body > p font i').eq(--index).filter('u').length == 0);
console.log($('body > p font u, body > p font i').eq(index).text());
}

相当简单的问题。我正在针对选择器过滤器迭代 jQuery 结果集,直到找到匹配项,然后在结果集中向上爬。

这个循环运行的时间越长,它变得越慢,几乎呈指数级增长。

最佳答案

您在每次迭代时都在 DOM 树中搜索,这是一项昂贵的操作,解决方案是缓存:

var nodes = $('body > p font i');
for (var i = 0, size = nodes.length; i < size; i++) {
current = [nodes.eq(index),nodes.eq(index).index('body > p font u, body > p font i')];
}

关于javascript - 为什么这个循环会逐渐变慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41065644/

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