为什么这段代码
for(var i = 0; i < array.length; ++i) {
array[i]["bla"] = "check";
}
完美地工作,而阵列在这里,根据萤火虫,未定:
for(var i = 0; i < array.length; ++i) {
$.ajax({
type: "POST",
url: "my url",
data: "data here",
success: function() {
array[i]["bla"] = "check";
}
});
}
我该如何解决这个问题?
答案 0 :(得分:2)
由于闭包的工作原理,i
的值总是等于回调中的array.length
,因为在循环完成之后它是等于的(毕竟,i < array.length
是假的。而且这个位置总是未定义的。您需要在循环内重新绑定i
以使当前值&#34;坚持&#34;。不幸的是,在标准JS中执行此操作的唯一方法是使用另一个函数,例如:
for (...; i++) {
(function(boundI) {
// boundI is now bound to the current value of i in the current scope
// If you want, you can call boundI just "i", but make sure you understand
// how scopes work in JS before you do.
$.ajax({
...
success: function() {
array[boundI]["bla"] = "check";
}
});
})(i); // pass in the current value of the loop index which gets bound to boundI
}
答案 1 :(得分:0)
您可以进行同步通话:
for(var i = 0; i < array.length; ++i) {
$.ajax({
type: "POST",
async: false, //This does the magic
url: "my url",
data: "data here",
success: function() {
array[i]["bla"] = "check";
}
});
}
或者,保持同步性
var array = ...
function loadElement(i){
if(i == array.length) return;
$.ajax({
type: "POST",
url: "my url",
data: "data here",
success: function() {
array[i]["bla"] = "check";
loadElement(i+1);
}
});
}
loadElement(0);
希望这会有所帮助。干杯