我有一个函数,它以字典[{}]
列表作为参数。它通过向其添加新的key: value
对来操作此dicts列表,其中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;
}
我不知道为什么会发生这种情况,有人会帮忙吗?
答案 0 :(得分:3)
您似乎认为您要将fileList
的副本添加到每个字典中,但实际上是将相同的 fileList
添加到每个(也就是说,每个都是对同一个对象的引用),正如@vlaz指出的那样,当你清空原文时,你实际上是在清空每个字典中出现的内容。