推送到多维数组 returns 填充数组

Push to multidimensional array returns filled array

我的预期输出是一个数组,其中包含一个具有此算法的 return 值的数组,以及其他 4 个空数组。但出于某种原因,我得到了 5 个充满数据的数组,我很困惑。如果有帮助,您可以在 repl 上查看我的代码。

const getResults = (Algorithms) => {
  const testCases = [0,1,3,2,10,17,97,51];
  let results = Array(5);
  results.fill([]);

  for(const test of testCases) {
      results[0].push(Algorithms.isPrime(test));
  }

  return(results);
}

getResults(Algorithms);
results.fill([]);

正在将 相同的 数组放入 results 的每个插槽中 - 推到一个推到它们。

基本上你有:

let x = [];
results.fill(x);
// [x, x, x, x, x]

然后你正在修改 x

如果需要,每个插槽需要一个不同的数组

results = Array(5).fill().map(() => []);

它会起作用。

Array.from 是您要找的东西。替换那些泳道:

let results = Array(5)
results.fill([])

与:

const res = Array.from({length: 5}, _ => [])

console.log(res)