我正在研究chrome extension (StackEye),根据我的用例,我必须在循环中从localStorage中删除一些对象。这是我的代码,
for (var i = 0; i < objectKeys.length; i++) {
chrome.storage.local.remove(objectKeys[i], function() {
// Do something with objectKeys[i] like remove the corresponding element from DOM
// Show notification to user that objectKeys[i] item has been removed
});
}
你可以看到我在这里使用Closure
来识别删除了哪个特定对象,并在以后对其执行某些操作。但问题是
当匿名方法(删除成功处理程序)被调用时,可能会在循环中更改i的值并且它会影响处理程序中的操作。
我该如何解决这个问题?
答案 0 :(得分:1)
我们可以使用递归函数而不是for
循环
var len = objectKeys.length;
function asyncLoop(count) {
chrome.storage.local.remove(objectKeys[count], function() {
if(count < len) {
asyncLoop(count++);
}
});
}
asyncLoop(0);
答案 1 :(得分:0)
尝试在闭包范围内使用变量,以便稍后访问。
for (var i = 0; i < objectKeys.length; i++) {
var myobject = objectKeys[i]; //this variable is in the scope of the closure
chrome.storage.local.remove(myobject, function() {
// Do something with objectKeys[i] like remove the corresponding element from DOM
// Show notification to user that objectKeys[i] item has been removed
});
}