【发布时间】:2023-03-26 05:47:02
【问题描述】:
使用 laravel,我们正在开发的系统在“onready”事件的这个视图上崩溃。看了代码,发现问题出在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 时崩溃。
我们做了一个伪修复是一个 try catch 代码块,因为无论数组中有多少项,这个问题都会持续存在,并且总是到达最后一个索引 + 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.
}
});
}
});
我们做了简单而愚蠢的修复,但我们还没有发现为什么会发生这种情况,for循环如何,假设data.auctions.length = 3,打印0,1,2,3?
【问题讨论】:
-
回调中的代码(您放置
try...catch的位置将在循环结束后运行,并将在该最终状态下引用j。所以,在所有情况下都是j = data.auctions.length。
标签: javascript php laravel-5