【问题标题】:JavaScript Function that creates 4 random numbers that push to an array?创建4个随机数推送到数组的JavaScript函数?
【发布时间】:2026-02-08 12:45:02
【问题描述】:

不要这样做:

var crystalValues = [];
crystalValues[0] = Math.floor(Math.random()*12+1),
crystalValues[1] = Math.floor(Math.random()*12+1),
crystalValues[2] = Math.floor(Math.random()*12+1),
crystalValues[3] = Math.floor(Math.random()*12+1),  

如何创建一个返回 4 个随机数的函数?

【问题讨论】:

    标签: javascript arrays function loops


    【解决方案1】:

    下面的函数创建一个随机整数数组。

    count 设置多少,minmax 设置最小和最大随机值

        function createRandomArray(count,min,max){
            const rand = () =>  Math.floor( Math.random() * (max - min) + min);
            const vals = [];
            while(count-- > 0){ vals.push(rand()) }
            return vals;
        }
        console.log(createRandomArray(4,1,13));
        
        

    您可以将它们分配给另一个数组,如下所示

    const crystalValues = [];
    crystalValues.push(...createRandomArray(4,1,13))
    

    或者直接分配它们

    const crystalValues = createRandomArray(4,1,13);
    

    【讨论】:

      【解决方案2】:

      您可以简单地使用Array.from()

      var gen = () => {
      	return Array.from({length: 4}, () => Math.floor( Math.floor(Math.random()*12+1)));
      }
      
      console.log(gen());

      【讨论】:

      • 我怎样才能确保这些数字永远不会相等?
      【解决方案3】:

      使用 for 循环。

      试试这个:

      var crystalValues = [];
      
      for(var i = 0;i < 4;i++){
        crystalValues.push(Math.floor(Math.random()*12+1))
      }
      
      console.log(crystalValues);
      

      【讨论】:

      • 我怎样才能确保这些数字永远不会相等?
      【解决方案4】:

      如果您想节省键入函数的时间,那么 for 循环就可以解决问题。

      random4() {
          var crystalValues = [];
          for (var i=0; i < 4 ; i++) {
              randomNumber = Math.floor(Math.random()*12+1);
              while (crystalValues.indexOf(randomNumber) !== -1) {
                  randomNumber = Math.floor(Math.random()*12+1);
              }
              crystalValues[i] = randomNumber;
          }
          return crystalValues;
      }
      

      【讨论】:

      • 我怎样才能确保这些数字永远不会相等?
      • 我编辑了我的代码向你展示:添加一个 while 循环检查新随机数的索引,直到你得到一个唯一的。只要确保如果您更改代码,您不会以无限循环结束