与laravel合作,我们正在开发的系统在这个“就绪”事件的观点上崩溃了。在查看了代码之后,我们发现问题在for循环中。
$(document).ready(function() {
var url = "{{ route('routeToGetAuctions') }}";
$.ajax({
url : url,
type : "GET"
})
.done(function(data) {
for (var j = 0; j < data.auctions.length; j++) {
...
$('#object').downCount(data.auctions[j].auction, {
startDate: data.auctions[j].startDate,
endDate: data.auctions[j].endDate,
offset: data.auctions[j].offset
}, function() {
//Class management to show the auctions
finishedAuctions.push(data.auctions[j].auction);
$('#countdown-bg-'+data.auctions[j].auction).removeClass('bg-primary');
$('#countdown-bg-'+data.auctions[j].auction).addClass('bg-secondary');
$('#progress-'+data.auctions[j].auction).removeClass('bg-primary');
$('#progress-'+data.auctions[j].auction).addClass('bg-secondary');
});
}
});这很适合我们需要的..。但是,假设存在3个可用的拍卖,data.auctions.length的值为3,并且执行console.log('value of j: ' + j)调试for循环时,它会以某种方式打印:
value of j: 0
value of j: 1
value of j: 2
value of j: 3然后,当它试图到达大小为3 (0,1,2)的数组的索引3时崩溃。
我们所做的伪修复是一个尝试捕获代码块,因为无论数组中存在多少项,这个问题仍然存在,并且总是达到最后一个索引+ 1:
$(document).ready(function() {
var url = "{{ route('routeToGetAuctions') }}";
$.ajax({
url : url,
type : "GET"
})
.done(function(data) {
for (var j = 0; j < data.auctions.length; j++) {
...
$('#object').downCount(data.auctions[j].auction, {
startDate: data.auctions[j].startDate,
endDate: data.auctions[j].endDate,
offset: data.auctions[j].offset
}, function() {// Try Catch to fix unknown problem with loop
try {
finishedAuctions.push(data.auctions[j].auction);
$('#countdown-bg-'+data.auctions[j].auction).removeClass('bg-primary');
$('#countdown-bg-'+data.auctions[j].auction).addClass('bg-secondary');
$('#progress-'+data.auctions[j].auction).removeClass('bg-primary');
$('#progress-'+data.auctions[j].auction).addClass('bg-secondary');
} catch (e) {
//here the index exception is prevented and the view won't crash.
}
});
}
});我们所做的简单而愚蠢的修复,但我们还没有弄清楚为什么会发生这种情况,假设是data.auctions.length = 3的for循环是如何打印0,1,2,3的
发布于 2019-12-18 17:00:59
倒计时结束后,将执行downCount回调。这意味着这不是马上执行的。
因此,循环不断地递增'j‘,这意味着一旦执行回调,'j’将位于最大值。
这里简单地展示了你正在经历的事情。它将多次记录“5”,而不是0,1,2,3,4。之所以是5,是因为I会先增加,然后检查条件!--这正是代码崩溃的原因。因为j最多增加一个数组长度,所以检查条件!
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i)
}, 100)
}
最简单的解决方案是使用let而不是var,因为它们是受作用域约束的。
for (let i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i)
}, 100)
}
如果您无法访问let,则可以使用闭包
for (var i = 0; i < 5; i++) {
(function(val) {
setTimeout(function() {
console.log(val)
}, 100)
})(i)
}
@Vlaz对他的范围界定的文章是正确的。这是一个伟大的阅读,以进一步启发你!
https://stackoverflow.com/questions/59396665
复制相似问题