javascript - 为什么这个函数返回相同的 id?
问题描述
const errorListWithTheSameId = new Array(2).fill({
fileName: 'SG100132019.pdf',
contentType: 'application/pdf',
});
const correctList = [{
fileName: 'SG100132019.pdf',
contentType: 'application/pdf',
}, {
fileName: 'SG100132019.pdf',
contentType: 'application/pdf',
}];
const generate = function() {
let uidIndex = 0;
return function generateUniqueId(key) {
uidIndex += 1;
return `id-${key}-${Date.now()}-${uidIndex}`;
};
};
const generateUniqueId = generate();
const addIdForList = (fileList) => {
const newFileList = [];
for (const item of fileList) {
item._id = generateUniqueId(item.fileName);
newFileList.push(item);
}
return newFileList;
}
console.log(addIdForList(errorListWithTheSameId), 'errorListWithTheSameId');
console.log(addIdForList(correctList), 'correctList');
请看一下这段代码。由normalList
new Array 创建并由对象填充。并且anotherList
是直接创建的。当我使用一个函数为其添加一个 id 时,第一个数组得到相同的 id,这不是我所期望的。你能解释一下为什么会这样吗?我该如何解决。非常感谢。
解决方案
当您使用 .fill() 时,参数是对对象的引用,因此每个数组元素都是同一个对象。
这是一个如何使用 Array.from() 确保每个数组元素不同的示例
const normalList = Array.from({
length: 2
}, () => ({
fileName: 'SG100132019.pdf',
contentType: 'application/pdf',
}));
推荐阅读
- ios - 在文本视图中使用 separatorBy 函数获取范围
- swift - 从文件中解析时,Swift字符串插值不起作用
- ruby-on-rails - Rails:搜索过滤
- computer-science - 证明 PATH 问题不是 NP 完全问题
- sql - Ecto 模型查询通过一对一映射返回相关对象
- node.js - PM2下运行的节点APP无法运行子进程
- linkedin - 调用 /v2/me 时出现“资源我不存在”API 错误
- android - Android 10 崩溃(layout/abc_screen_simple 第 17 行中的 InflateException)
- apache-spark - 在阅读多分区 kafka 主题时,如何启动和调用 spark 结构化流式消费者?
- javascript - 退出用户后从 Cloud Firestore 中清理用户数据