gpt4 book ai didi

Javascript:字典 'key' 值在 for 循环之外变为 null

转载 作者:行者123 更新时间:2023-11-28 18:20:49 24 4
gpt4 key购买 nike

我有一个函数,它接受字典列表[{}]作为参数。它通过添加一个新的 key: value 对来操作这个字典列表,其中 value 也是一个字典列表。这就是该函数的样子,我添加了注释来解释它。

function addFilesToProjects(nonUniqueArray, lists) {
var fileList = [{}]; //this will contain the list of dictionaries that I want to add as a key to the array 'nonUniqueArray'
var filesArray = []; //this was just for testing purposes because I want to access the modified version of nonUniqueArray outside the function, which I'm not able to (it shows undefined for the new key:value pair)
for (var i = 0; i < nonUniqueArray.length; i++) {
lists.forEach(function (list) {
fileNameString = JSON.stringify(list['name']).slice(2, -2);
if (fileNameString.indexOf(nonUniqueArray[i]['title']) !== -1 && fileNameString !== nonUniqueArray[i]['title']) {
fileList.push({
'name': fileNameString
});
}
});
nonUniqueArray[i]['files'] = fileList;

//this logs out the right key:value pair to the console
console.log(nonUniqueArray[i]);

filesArray.push(nonUniqueArray[i]);
while (fileList.length > 0) {
fileList.pop();
}
}

//however, now I get everything as before except the new 'files' key has empty list [] as its value :(
console.log(nonUniqueArray);

return filesArray;
}

我不知道为什么会发生这种情况,有人可以帮忙吗?

最佳答案

您似乎认为您正在将 fileList副本添加到每个字典中,但实际上正在添加相同 fileList 到每个(即,每个都是对同一对象的引用)中,这样,正如 @vlaz 指出的那样,当您清空原始文件时,您实际上清空了每个字典中出现的内容。

关于Javascript:字典 'key' 值在 for 循环之外变为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39942322/

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