从JavaScript数组中获取随机值

时间:2010-12-29 00:04:44

标签: javascript

考虑:

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

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

29 个答案:

答案 0 :(得分:1206)

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

答案 1 :(得分:79)

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

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

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

var myRandomElement = myArray.randomElement()

请注意,这会为所有数组添加一个属性,因此,如果您使用for..in循环使用.hasOwnProperty(),则应使用for (var prop in myArray) { if (myArray.hasOwnProperty(prop)) { ... } }

{{1}}

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

答案 2 :(得分:54)

如果您的项目中已包含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 :(得分:19)

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

在@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)

答案 4 :(得分:19)

原型方法

如果您打算多次获取随机值,则可能需要为其定义一个函数。

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

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 :(得分:10)

libcgcc -Wall -Wextra -g快得多,因此在使用UI元素生成输出时进行性能优化时,gdb会赢得游戏。 MORE INFO

~~

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

~~

答案 6 :(得分:10)

最短版本:

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

答案 7 :(得分:8)

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

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

数组的第二部分是Why does [5,6,8,7][1,2] = 8 in JavaScript?

中描述的访问操作

答案 8 :(得分:4)

编辑数组原型可能是有害的。这是完成这项工作的简单功能。

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 :(得分:3)

如果你想把它写在一行上,比如Pascual的解决方案,另一个解决方案就是使用ES6的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并使用单独的函数)是你的方法。

答案 10 :(得分:2)

递归,独立函数,可以返回任意数量的项目(与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])
}

答案 11 :(得分:2)

简单功能:

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

OR

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

OR

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

答案 12 :(得分:2)

Faker.js具有许多用于生成随机测试数据的实用程序函数。在测试套件的上下文中这是一个很好的选择:

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

正如评论者提到的,您通常不应在生产代码中使用此库。

答案 13 :(得分:2)

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);

答案 14 :(得分:2)

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

这是ES2015:

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

代码的工作原理是选择介于0和数组长度之间的随机数,然后在该索引处返回该项。

答案 15 :(得分:1)

我找到了绕过最佳答案的复杂方法,只需将变量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>

答案 16 :(得分:1)

static generateMonth() { 
const theDate = ['January', 'February', 'March']; 
const randomNumber = Math.floor(Math.random()*3);
return theDate[randomNumber];
};

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

答案 17 :(得分:1)

要获取crypto-strong随机项目表单数组,请使用

let rndItem = a=> a[rnd()*a.length|0];
let rnd = ()=> crypto.getRandomValues(new Uint32Array(1))[0]/2**32;

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

console.log( rndItem(myArray) )

答案 18 :(得分: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)循环

答案 19 :(得分:0)

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

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;
}

答案 20 :(得分:0)

另一种简便方法:

var myArray = ['keke','keko','cano','halo','zirto'];

var randomValue = myArray[Math.round((Math.random()*1000))%myArray.length];

答案 21 :(得分:0)

randojs.com使它成为一线:

rando(['January', 'February', 'March']).value

您必须说“ .value”,因为如果愿意,您还可以选择获取随机选择的索引。您只需要将其添加到html文档的头部,就可以轻松地随机执行几乎任何您想做的事情。来自数组的随机值,随机的jquery元素,对象的随机属性,甚至在需要时防止重复。

<script src="https://randojs.com/1.0.0.js"></script>

答案 22 :(得分:0)

寻找真正的一线客,我来了:

['January', 'February', 'March'].reduce((a, c, i, o) => { return o[Math.floor(Math.random() * Math.floor(o.length))]; })

答案 23 :(得分:0)

通过在数组原型上添加方法,您可以轻松获得随机值。

在此示例中,您可以从数组中获取单个或多个随机值。

您可以通过点击代码段按钮来运行测试代码。

Array.prototype.random = function(n){
  if(n&&n>1){
    const a = [];
    for(let i = 0;i<n;i++){
      a.push(this[Math.floor(Math.random()*this.length)]);
    }
    return a;
  } else {
    return this[Math.floor(Math.random()*this.length)];
  }
}

const mySampleArray =  ['a','b','c','d','e','f','g','h'];

mySampleArray.random(); // return any random value etc. 'a', 'b'
mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d']

alert(mySampleArray.random());
alert(mySampleArray.random(3));

答案 24 :(得分:0)

方法一:

  • 使用 Math.random() 函数获取(0-1, 1)之间的随机数 独家)。
  • 乘以数组长度得到数字 之间(0-arrayLength)。
  • 使用 Math.floor() 获取索引范围 从(0 到 arrayLength-1)。
<块引用>

const arr = ["foo","bar"];
const randomPickedString=arr[Math.floor(Math.random() * arr.length)]; console.log(randomlyPickedString);

方法二:

  • random(a, b) 方法用于在(a 到 b,b 不包括)之间生成一个数。
  • 取下限值以将数字范围从(1 到 arrayLength)。
  • 减 1 得到范围从(0 到 arrayLength-1)的索引。
<块引用>

const arr = ["foo","bar"];
const randomPickedString=arr[Math.floor(random(1, 5))-1]; console.log(randomlyPickedString);

答案 25 :(得分:0)

如果你需要多次获取一个随机项目,那么,显然你会使用一个函数。一种方法是使该函数成为 Array.prototype 的方法,但这通常会让您因为篡改内置原型而受到谴责。

但是,您可以将方法添加到特定数组本身:

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

这样您就可以随意使用 months.random(),而不会干扰通用 Array.prototype

与任何随机函数一样,您冒着连续获得相同值的风险。如果您不想这样,则需要使用另一个属性跟踪先前的值:

months.random=function() {
    var random;
    while((random=this[Math.floor(Math.random()*this.length)]) == this.previous);
    this.previous=random;
    return random;
};

答案 26 :(得分:-1)

以下是如何操作的示例:

$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)];

答案 27 :(得分:-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;
    }
}

答案 28 :(得分:-3)

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

请尝试以下代码..

//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);