首页 > 解决方案 > 为什么这个函数返回相同的 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');

请看一下这段代码。由normalListnew Array 创建并由对象填充。并且anotherList是直接创建的。当我使用一个函数为其添加一个 id 时,第一个数组得到相同的 id,这不是我所期望的。你能解释一下为什么会这样吗?我该如何解决。非常感谢。

标签: javascript

解决方案


当您使用 .fill() 时,参数是对对象的引用,因此每个数组元素都是同一个对象。

这是一个如何使用 Array.from() 确保每个数组元素不同的示例

const normalList = Array.from({
  length: 2
}, () => ({
  fileName: 'SG100132019.pdf',
  contentType: 'application/pdf',
}));


推荐阅读