gpt4 book ai didi

Javascript 跳过 For 循环中的间隔

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

我在 JavaScript 中有一个 for 循环,它会定期跳过间隔,但我无法确定原因。

console.log(parseInt($('input.num-to-add').val()));
numToAdd = parseInt($('input.num-to-add').val());
console.log(numToAdd);
for(i=0;i<numToAdd;i++){
console.log('Running loop for ' + i + '...');
// the following code won't mean much
// but it was noted that the full code should be present
table.find('tbody').prepend(data.html);
var row = table.find('tbody #add-location-row').first();
rowInit(row);
}

如您所见,我几乎每一步都在 console.log 中,但我无法确定问题所在。问题本身在控制台输出中得到了很好的说明。例如,如果 input.num-to-add 的值为 8,这是我在控制台中看到的:

8
8
Running loop for 0...
Running loop for 6...
Running loop for 7...

我真的看不出问题出在哪里。在我看来,这是非常简单和基本的代码,但它以某种我根本无法确定的方式中断。

最佳答案

正如许多其他人已经在评论部分指出的那样,这肯定会发生,因为您使用名为 i全局变量作为循环变量。如果您在 rowInit 中使用相同的全局变量 i,则会干扰此循环。解决方案很简单,始终使用正确范围的变量:

for(var i=0;i<numToAdd;i++){
console.log('Running loop for ' + i + '...');
// the following code won't mean much
// but it was noted that the full code should be present
table.find('tbody').prepend(data.html);
var row = table.find('tbody #add-location-row').first();
rowInit(row);
}

或者更好:

for(let i=0;i<numToAdd;i++){

关于Javascript 跳过 For 循环中的间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41938353/

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