gpt4 book ai didi

javascript - 成功函数中的数组未定义

转载 作者:行者123 更新时间:2023-11-29 22:32:09 26 4
gpt4 key购买 nike

为什么这段代码

for(var i = 0; i < array.length; ++i) {
array[i]["bla"] = "check";
}

工作完美,而数组在这里,根据 Firebug ,未定义:

for(var i = 0; i < array.length; ++i) {
$.ajax({
type: "POST",
url: "my url",
data: "data here",
success: function() {
array[i]["bla"] = "check";
}
});
}

我该如何解决这个问题?

最佳答案

由于闭包的工作方式,i 的值总是等于 array.length在回调中,因为这就是循环完成后等于的值(毕竟,i < array.length 为假)。那个位置总是不确定的。需要重新绑定(bind)i在循环内部使当前值“坚持”。不幸的是,在标准 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
}

关于javascript - 成功函数中的数组未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6555980/

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