You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改JavaScript代码避免Math.random()生成重复的6位随机数?

How to Generate Unique 6-Digit Random Numbers (100000-999999)

Got it, let's tackle this problem. Your current code generates a valid 6-digit random number, but since it doesn't track what's already been created, duplicates are bound to pop up eventually. Here are two practical approaches to fix this, depending on how many unique numbers you need:

Approach 1: Track Used Numbers (Great for Smaller Sets)

If you only need to generate a handful of unique numbers, the simplest way is to keep a record of every number you've already created. We'll use a Set here because checking if a number exists in a Set is super fast (way quicker than an array's includes() method).

// Keep track of numbers we've already generated
const usedNumbers = new Set();

function getUnique6DigitRandom() {
  let randomNum;
  // Keep generating numbers until we get one that's not in our set
  do {
    // Same logic as your original code to get a 6-digit number
    randomNum = Math.floor(Math.random() * 900000) + 100000;
  } while (usedNumbers.has(randomNum));
  
  // Add the new number to our set so we don't reuse it
  usedNumbers.add(randomNum);
  return randomNum;
}

// Example: Generate 5 unique numbers and display them
for (let i = 0; i < 5; i++) {
  document.write(getUnique6DigitRandom() + '<br>');
}

Every time you call getUnique6DigitRandom(), it'll spit out a number you haven't seen before—no duplicates guaranteed.

Approach 2: Shuffle All Possible Numbers (Best for Large/Full Sets)

If you need to generate a lot of unique numbers (or even all 900,000 possible 6-digit numbers), the first approach might start slowing down once most numbers are already used (it'll keep retrying until it finds an unused one). Instead, we can create a list of every possible 6-digit number, shuffle it, then pull numbers from the shuffled list.

We'll use the Fisher-Yates Shuffle here—it's a fair, efficient way to randomize an array without bias.

function generateShuffled6Digits() {
  const all6DigitNumbers = [];
  // Fill the array with every 6-digit number from 100000 to 999999
  for (let num = 100000; num <= 999999; num++) {
    all6DigitNumbers.push(num);
  }
  
  // Fisher-Yates Shuffle to randomize the array
  for (let i = all6DigitNumbers.length - 1; i > 0; i--) {
    const randomIndex = Math.floor(Math.random() * (i + 1));
    // Swap elements to shuffle
    [all6DigitNumbers[i], all6DigitNumbers[randomIndex]] = [all6DigitNumbers[randomIndex], all6DigitNumbers[i]];
  }
  
  return all6DigitNumbers;
}

// Get our shuffled list of unique numbers
const shuffledNumbers = generateShuffled6Digits();

// Example: Grab the first 10 unique numbers and display them
for (let i = 0; i < 10; i++) {
  document.write(shuffledNumbers[i] + '<br>');
}

This way, every number in shuffledNumbers is unique and randomly ordered. You can just keep pulling from the array until you run out of numbers—no checks needed.

A quick note: Storing 900,000 numbers in an array uses barely any memory (roughly 7MB), so this is totally feasible in both browser and server environments.

内容的提问来源于stack exchange,提问作者Graham Jansen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:21:01