gpt4 book ai didi

Javascript 拼接 while push 在事件处理程序中

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

假设你有一个像这样的数组:

var arr= [{id:121, v:'a'}, {id:232, 'b'}];

你需要找到 id: 232 并删除它,所以你可以这样做:

for (var i = arr.length; i--;) {
if (arr[i].id === 232) {
arr.splice(i, 1);
}
};

假设有一个事件处理程序将项目添加到数组中,例如:

arr.push( {id:443, 'c'} );   

是否有可能在 for 循环迭代时调用事件处理程序?如果是这样,则 splice(i,1) 将删除错误的数组索引。

由于 javascript 是单线程的,它是否足够智能以在处理事件之前完成 for 循环?

最佳答案

有趣的问题。我做了一个小测试来检查真实情况:http://jsfiddle.net/wared/ERjJj/ .看起来点击事件发生在循环完成后(仅使用 Chrome 测试)。

<ol>
<li>Open your browser console.</li>
<li>Click <button>start</button>.</li>
<li>The console prints <code>wait...</code>.</li>
<li>Click again, one or more times, anywhere in this panel.</li>
<li>Wait a few seconds until the console prints <code>done!</code>.</li>
<li>The console prints <code>click</code>.</li>
</ol>
$(document).click(function () {
console.log('click');
});
$('button').one('click', function click() {
var i = 0, b = this;
console.log('wait...');
while (i++ < 1E10) 1+1;
console.log('done!');
setTimeout(function () {
$(b).one('click', click);
}, 10);
});

如果有任何问题,请随时告诉我。

关于Javascript 拼接 while push 在事件处理程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22075891/

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