gpt4 book ai didi

JavaScript 闭包 : return values disunderstanding

转载 作者:行者123 更新时间:2023-12-02 15:20:37 28 4
gpt4 key购买 nike

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?
我在网上搜索过但找不到好的答案。希望在这里我能克服它。谢谢。

最佳答案

这是因为关闭。了解它 herehere .

这应该可以解决您的问题:

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/

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