首页 文章

从JavaScript数组中获取随机值

提问于
浏览
548

考虑:

var myArray = ['January', 'February', 'March'];

如何使用JavaScript从此数组中选择随机值?

23 回答

  • 7

    获取随机元素的通用方法:

    let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
    let months = random_elems(some_array, 3);
    
    console.log(months);
    
    function random_elems(arr, count) {
      let len = arr.length;
      let lookup = {};
      let tmp = [];
    
      if (count > len)
        count = len;
    
      for (let i = 0; i < count; i++) {
        let index;
        do {
          index = ~~(Math.random() * len);
        } while (index in lookup);
        lookup[index] = null;
        tmp.push(arr[index]);
      }
    
      return tmp;
    }
    
  • 75

    如果您的项目中已包含underscorelodash,则可以使用_.sample .

    // will return one item randomly from the array
    _.sample(['January', 'February', 'March']);
    

    如果您需要随机获得多个项目,可以将其作为下划线中的第二个参数传递:

    // will return two items randomly from the array using underscore
    _.sample(['January', 'February', 'March'], 2);
    

    或者在lodash中使用_.sampleSize方法:

    // will return two items randomly from the array using lodash
    _.sampleSize(['January', 'February', 'March'], 2);
    
  • 3

    假设您要选择与上次不同的随机项目(不是非常随机,但仍然是常见要求)...

    在@Markus的答案基础上,我们可以添加另一个原型函数:

    Array.prototype.randomDiffElement = function(last) {
       if (this.length == 0) {
          return;
       } else if (this.length == 1) {
          return this[0];
       } else {
          var num = 0;
          do {
             num = Math.floor(Math.random() * this.length);
          } while (this[num] == last);
          return this[num];
       }
    }
    

    并执行如下:

    var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement)
    
  • 0

    编辑阵列原型可能是有害的 . 这是一个简单的功能来完成这项工作 .

    function getArrayRandomElement (arr) {
      if (arr && arr.length) {
        return arr[Math.floor(Math.random() * arr.length)];
      }
      // The undefined will be returned if the empty array was passed
    }
    

    用法:

    // Example 1
    var item = getArrayRandomElement(['January', 'February', 'March']);
    
    // Example 2
    var myArray = ['January', 'February', 'March'];
    var item = getArrayRandomElement(myArray);
    
  • 9
    static generateMonth() { 
    const theDate = ['January', 'February', 'March']; 
    const randomNumber = Math.floor(Math.random()*3);
    return theDate[randomNumber];
    };
    

    您为数组设置了一个常量变量,然后您有另一个在数组中的三个对象之间随机选择的常量,然后该函数只返回结果 .

  • 2

    ~~Math.Floor() 快得多,因此在使用UI元素生成输出时进行性能优化时, ~~ 赢得游戏 . MORE INFO

    var rand = myArray[~~(Math.random() * myArray.length)];
    

    但是如果你知道数组将有比你想要在Bitwise运算符和 Math.Floor() 之间重新考虑的数百万个元素一样,那么按位运算符的行为就像大数字一样奇怪 . 请参阅以下使用输出解释的示例 . MORE INFO

    var number = Math.floor(14444323231.2); // => 14444323231
    var number = 14444323231.2 | 0; // => 1559421343
    
  • 0

    使用Faker.js

    const Faker = require('faker');
    Faker.random.arrayElement(['January', 'February', 'March']);
    
  • -3

    我已经找到了绕过最佳答案的复杂方法,只需将变量rand连接到另一个变量,该变量允许在调用myArray [];内部显示该数字 . 通过删除创建的新阵列并解决其中的复杂问题,我提出了一个可行的解决方案:

    <!DOCTYPE html>
    <html>
    <body>
    
    <p id="demo"></p>
    
    <script>
    
    var myArray = ['January', 'February', 'March', 'April', 'May'];    
    
    var rand = Math.floor(Math.random() * myArray.length);
    
    var concat = myArray[rand];
    
    function random() {
       document.getElementById("demo").innerHTML = (concat);
    }
    </script>
    
    <button onClick="random();">
    Working Random Array generator
    </button>
    
    </body>
    </html>
    
  • -1

    这项工作对我而言毫无重复的魅力 .

    var Random_Value = Pick_Random_Value(Array);
    

    function Pick_Random_Value(IN_Array) 
    {
        if(IN_Array != undefined && IN_Array.length > 0)
        {
            var Copy_IN_Array = JSON.parse(JSON.stringify(IN_Array));
            if((typeof window.Last_Pick_Random_Index !== 'undefined') && (window.Last_Pick_Random_Index !== false))
            {
                if(Copy_IN_Array[Last_Pick_Random_Index] != undefined)
                {
                    Copy_IN_Array.splice(Last_Pick_Random_Index,1);
                }
            }
    
            var Return_Value = false;
    
            if(Copy_IN_Array.length > 0)
            {
                var Random_Key = Math.floor(Math.random() * Copy_IN_Array.length);
                Return_Value = Copy_IN_Array[Random_Key];
            }
            else
            {
                Return_Value = IN_Array[Last_Pick_Random_Index];
            }
    
            window.Last_Pick_Random_Index = IN_Array.indexOf(Return_Value);
            if(window.Last_Pick_Random_Index === -1)
            {
                for (var i = 0; i < IN_Array.length; i++) 
                {
                    if (JSON.stringify(IN_Array[i]) === JSON.stringify(Return_Value)) 
                    {
                        window.Last_Pick_Random_Index = i;
                        break;
                    }
                }
            }
    
    
            return Return_Value;
        }
        else
        {
            return false;
        }
    }
    
  • 2

    创建一个随机值并传递给数组

    请尝试以下代码..

    //For Search textbox random value
    var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
    var rand = Math.floor(Math.random() * myPlaceHolderArray.length);
    var Placeholdervalue = myPlaceHolderArray[rand];
    
    alert(Placeholdervalue);
    
  • 17

    递归,独立函数,可以返回任意数量的项目(与lodash.sampleSize相同):

    function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
        const elements = [];
    
        function getRandomElement(arr) {
            if (elements.length < numberOfRandomElementsToExtract) {
                const index = Math.floor(Math.random() * arr.length)
                const element = arr.splice(index, 1)[0];
    
                elements.push(element)
    
                return getRandomElement(arr)
            } else {
                return elements
            }
        }
    
        return getRandomElement([...array])
    }
    
  • 1066

    原型方法

    如果您计划大量获取随机值,则可能需要为其定义函数 .

    首先,将它放在代码中的某处:

    Array.prototype.sample = function(){
      return this[Math.floor(Math.random()*this.length)];
    }
    

    现在:

    [1,2,3,4].sample() //=> a random element
    

    代码根据CC0 1.0 license条款发布到公共领域 .

  • 5

    如果您有固定值(如月份名称列表)并想要一个单行解决方案

    var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]
    

    数组的第二部分是Why does [5,6,8,7][1,2] = 8 in JavaScript?中描述的访问操作

  • 47

    如果你想在一行上写它,比如Pascual 's solution, another solution would be to write it using ES6' s find函数(根据事实,随机选择 n 项中的一个的概率是 1/n ):

    var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));
    console.log(item);
    

    使用该方法进行测试,如果有充分的理由不将数组保存在单独的变量中 . 否则,其他答案( floor(random()*length 并使用单独的功能)是你的方法 .

  • 3
    var items = Array("elm1","elm2","elm3","elm4",...);
    
    var item = items[Math.floor(Math.random()*items.length)];
    
  • -1

    这与@Jacob Relkin的解决方案类似,但更为通用:

    这是ES2015:

    const randomChoice = arr => {
        const randIndex = Math.floor(Math.random() * arr.length);
        return arr[randIndex];
    };
    

    该代码通过选择0和数组长度之间的随机数,然后返回该索引处的项目来工作 .

  • 0

    在我看来,更好地搞乱原型,或者及时宣布原型,我更喜欢将它暴露在窗口中:

    window.choice = function() {
      if (!this.length || this.length == 0) return;
      if (this.length == 1) return this[0];
      return this[Math.floor(Math.random()*this.length)];
    }
    

    现在你的应用程序的任何地方都称它为:

    var rand = window.choice.call(array)
    

    这样你仍然可以正确使用 for(x in array) 循环

  • 2

    我发现将原型函数添加到Array类更简单:

    Array.prototype.randomElement = function () {
        return this[Math.floor(Math.random() * this.length)]
    }
    

    现在我只需键入以下内容即可获得随机数组元素:

    var myRandomElement = myArray.randomElement()
    

    请注意,这将向所有数组添加属性,因此如果使用 for..in 循环使用 .hasOwnProperty() ,则应使用 .hasOwnProperty()

    for (var prop in myArray) {
        if (myArray.hasOwnProperty(prop)) {
            ...
        }
    }
    

    (这对你来说可能是麻烦,也可能不是麻烦 . )

  • 1

    最短的版本:

    var myArray = ['January', 'February', 'March']; 
    var rand = myArray[(Math.random() * myArray.length) | 0]
    
  • 1

    var item = myArray[Math.floor(Math.random()*myArray.length)];

    或等效的较短版本:

    var item = myArray[(Math.random()*myArray.length)|0];

    示例代码:

    var myArray = ['January', 'February', 'March'];    
    var item = myArray[(Math.random()*myArray.length)|0];
    console.log('item:', item);
    
  • -1
    var rand = myArray[Math.floor(Math.random() * myArray.length)];
    
  • 18

    以下是如何执行此操作的示例:

    $scope.ctx.skills = data.result.skills;
        $scope.praiseTextArray = [
        "Hooray",
        "You\'re ready to move to a new skill", 
        "Yahoo! You completed a problem", 
        "You\'re doing great",  
        "You succeeded", 
        "That was a brave effort trying new problems", 
        "Your brain was working hard",
        "All your hard work is paying off",
        "Very nice job!, Let\'s see what you can do next",
        "Well done",
        "That was excellent work",
        "Awesome job",
        "You must feel good about doing such a great job",
        "Right on",
        "Great thinking",
        "Wonderful work",
        "You were right on top of that one",
        "Beautiful job",
        "Way to go",
        "Sensational effort"
      ];
    
      $scope.praiseTextWord = $scope.praiseTextArray[Math.floor(Math.random()*$scope.praiseTextArray.length)];
    
  • 2

    简单功能:

    var myArray = ['January', 'February', 'March'];
    function random(array) {
         return array[Math.floor(Math.random() * array.length)]
    }
    random(myArray);
    

    要么

    var myArray = ['January', 'February', 'March'];
    function random() {
         return myArray[Math.floor(Math.random() * myArray.length)]
    }
    random();
    

    要么

    var myArray = ['January', 'February', 'March'];
    function random() {
         return myArray[Math.floor(Math.random() * myArray.length)]
    }
    random();
    

相关问题