作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
function celebrityIDCreator(theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
theCelebrities[i]["id"] = function () {
return uniqueID + i;
};
};
return theCelebrities;
}
var actionCelebs = [
{ name: "Stallone", id: 0 },
{ name: "Cruise", id: 0 },
{ name: "Willis", id: 0 }
];
var createIdForActionCelebs = celebrityIDCreator(actionCelebs);
var stalloneID = createIdForActionCelebs[0];
console.log(stalloneID.id()); // 103
在前面的示例中,调用匿名函数时,i 的值为 3(数组的长度,然后递增)。将数字 3 添加到 uniqueID 中,为所有名人 ID 创建 103。因此,返回数组中的每个位置都会得到 id = 103,而不是预期的 100、101、102。
我读了回调函数文章,当我读不到这句话时,我的意思是如何解释我们总是得到 id=103?
我在网上搜索过但找不到好的答案。希望在这里我能克服它。谢谢。
最佳答案
这应该可以解决您的问题:
function celebrityIDCreator(theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
theCelebrities[i]["id"] = (function (index) {
return function () {
return uniqueID + index;
};
})(i);
}
return theCelebrities;
};
关于JavaScript 闭包 : return values disunderstanding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34118071/
这个问题已经有答案了: JavaScript closure inside loops – simple practical example (45 个回答) How do JavaScript cl
我是一名优秀的程序员,十分优秀!