我已经看过这个问题,但是我仍然停留在这个JavaScript closure inside loops – simple practical example
这是我的代码
template[prop['Name']] = [];
var processedCounter = -1;
$.each(prop.Properties, function (key, value) {
console.log(processedCounter + 'outside');
$.getJSON(value['Url']).done(function (jsres) {
console.log(processedCounter + 'inside');
var numItems = jsres[itemCount].length;
if (template[prop['Name']].length == 0) {
console.log('this should only be printed once');
for (var i = 0; i < numItems; i++) {
template[prop['Name']].push({});
}
}
processedCounter += 1;
});
});
有几个问题。首先,它会打印两次“仅应打印一次”消息。其次,因为在错误的时间增加了值,processedCounter的值必须为-1而不是0。