循环中的一个变量 - 如何在我的情况下修复它
A variable in a loop - how to fix it in my case?
我在函数内的循环中有一个变量:
function myHandler() {
for (var i = 0; i < items.length; i++) {
var currItem = items[i];
myObj.doSomething(function(data) {
console.log("ok");
console.log("My currItem id: " + currItem.id); // the last one of all in items
}, function(e) {
console.log("error");
console.log("My currItem id: " + currItem.id); // the last one of all in items
});
}
每次在 console.log() 中currItem.id
等于项目中的最后一个项目。明显地。我试图通过以下方式解决此问题:
function myHandler() {
for (var i = 0; i < items.length; i++) {
var currItem = items[i];
var currItem = (function(i2) {
return items[i2];
})(i);
myObj.doSomething(function(data) {
console.log("ok");
console.log("My currItem id: " + currItem.id); // the last one of all in items
}, function(e) {
console.log("error");
console.log("My currItem id: " + currItem.id); // the last one of all in items
});
}
仍然没有成功。为什么以及如何修复它?
像这样使用闭包:
正在返回的内部函数将记住创建它的环境。
function myHandler() {
for (var i = 0; i < items.length; i++) {
var currItem = items[i];
myObj.doSomething((function(currItem) {
return function(data) {
console.log("ok");
console.log("My currItem id: " + currItem.id);
}
})(currItem), (function(currItem) {
return function(e) {
console.log("error");
console.log("My currItem id: " + currItem.id);
}
})(currItem));
}
}
或:
使用 [].forEach
,因为每个迭代器回调都有自己的上下文,下次迭代不会覆盖该上下文。
如果 doSomething
方法是异步的,这意味着回调在 for 循环之后运行,则 currItem 将始终是最后一个。
回调函数有一个闭包,其中包含函数执行所需的所有信息,包括对变量currItem的引用。
因为它是一个引用,所以当循环结束时,currItem 的值是最后一项,然后才调用回调。
修复它的最简单方法是将 for 循环的内部调用移动到一个函数,该函数将接受变量 currItem 作为参数。这样变量就不会改变。
您可以使用数组的每个函数来做到这一点,如下所示:
items.forEach(function(currItem){
....
});
相关文章:
- 在我的情况下,如何进行http请求
- 如何在我的情况下禁用表单提交
- 在我的情况下,使用带有变量失败的 jquery 选择器
- 连接变量,在我的情况下背景样式损坏
- 如何在我的情况下设置日期格式
- 如何在我的情况下创建加载脚本
- angular如何在我的情况下设置服务
- 如何在我的情况下设置类名
- 在我的情况下,如何打开新的弹出窗口
- 函数在我的情况下无法执行
- 在我的情况下,如何选择某些孩子
- 如何在我的情况下切换链接
- res.download()在我的情况下不起作用
- 点击事件不'在我的情况下不会触发
- 在我的情况下,如何将对象添加到另一个对象中
- 在我的情况下,如何解决我的单元测试问题
- 不确定在我的情况下使用 ng-options 的最佳方法
- 在我的情况下,如何从 ajax 获取返回的数据
- 在我的情况下,如何将参数传递到函数中
- 在我的情况下,如何在角度中对对象列表进行排序