JavaScript Shuffle 函数无法正确洗牌

问题描述 投票:0回答:1

我正在尝试用 JavaScript 编写一个函数来打乱数组的元素。我想出了以下代码:

function shuffle(array) {
  // Loop through the array
  for (let i = 0; i < array.length; i++) {
    // Pick a random index from 0 to array length (incorrect)
    const j = Math.floor(Math.random() * array.length);
    
    // Swap the current element with the randomly picked element
    [array[i], array[j]] = [array[j], array[i]];
  }
  
  // Not returning anything (modifies original array - not ideal)
}

当我运行代码时,元素似乎没有随机洗牌。另外,原来的数组好像是直接修改的。

任何人都可以帮我找出这段代码的问题并提出改进建议吗?

如果解决方案能够解决以下问题,我将不胜感激:

确保适当的随机洗牌 返回一个新的打乱数组(不修改原始数组)

javascript arrays shuffle
1个回答
0
投票
function shuffle(array) {
  const newArray = array.slice(); // Create a shallow copy of the original array
  
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1)); // Pick a random index from 0 to i
    
    // Swap elements between i and j
    [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
  }
  
  return newArray; // Return the shuffled array
}
© www.soinside.com 2019 - 2024. All rights reserved.