生成不重复随机数有没有性能更好的方法?

const indRandom = (n, maxValue, minValue = 0) => {

  const nNumArray = [...Array(maxValue + 1).keys()];

  const resultArray = [];

  for (let i = 0; i < n; i++) {

    const randomNum = Math.floor((Math.random() * (((maxValue - minValue) + 1) - i)) + minValue);

    resultArray.push(nNumArray[randomNum]);

    nNumArray.splice(randomNum, 1);

  }

  console.log(resultArray);

  return resultArray;

};


indRandom(5, 10000);


梵蒂冈之花
浏览 568回答 1
1回答

湖上湖

function indRandom(n, max){&nbsp; var arr = [];&nbsp; for(var i = 0; i < n; i++){&nbsp; &nbsp; var item = Math.floor(Math.random() * max);&nbsp; &nbsp; if(arr.indexOf(item) > -1){ i--; continue; }&nbsp; &nbsp; else arr.push(item);&nbsp; }&nbsp; return arr;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript