Получение случайного значения из массива JavaScript

Рассмотрим:

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

Как выбрать случайное значение из этого массива с помощью JavaScript?

Ответ 1

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

Ответ 2

Я нашел еще проще добавить функцию прототипа в класс 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)) {
        ...
    }
}

(Это может быть или не быть проблемой для вас.)

Ответ 3

Если у вас уже есть underscore или lodash, который включен в ваш проект, вы можете используйте _.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);

или используйте метод _.sampleSize в lodash:

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

Ответ 4

Предположим, вы хотите выбрать случайный элемент, который отличается от последнего (не очень случайным, но все же общим требованием)...

Основываясь на ответе @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)

Ответ 5

Прототипный метод

Если вы планируете получать случайное значение много, вы можете определить для него функцию.

Сначала поставьте это в свой код где-нибудь:

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

Сейчас:

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

Код выпущен в общедоступное доменное пространство в соответствии с условиями лицензия CC0 1.0.

Ответ 6

~~ намного быстрее, чем Math.Floor(), поэтому, когда дело доходит до оптимизации производительности при выпуске с использованием элементов пользовательского интерфейса, ~~ выигрывает игра. БОЛЬШЕ ИНФОРМАЦИИ

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

Но если вы знаете, что массив будет иметь миллионы элементов, то вы можете пересмотреть между Побитовым оператором и Math.Floor(), поскольку побитовый оператор ведет себя странно с большими числами. См. Ниже пример, объясненный выходом. БОЛЬШЕ ИНФОРМАЦИИ

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

Ответ 7

Самая короткая версия:

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

Ответ 8

Если у вас есть фиксированные значения (например, список имен месяцев) и требуется однострочное решение

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

Вторая часть массива - операция доступа, описанная в Почему [5,6,8,7] [1,2] = 8 в JavaScript?

Ответ 9

Редактирование прототипа Array может быть вредным. Здесь это простая функция, чтобы сделать работу.

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

Ответ 10

Если вы хотите записать его в одной строке, например, в решении Pascual, другим решением было бы написать его с помощью функции поиска ES6 (исходя из того, что вероятность случайного выбора одного из элементов n равна 1/n):

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

Ответ 11

Рекурсивная автономная функция, которая может возвращать любое количество элементов (идентичное 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])
}

Ответ 12

Это похоже на, но более общее, чем решение @Jacob Relkin:

Это ES2015:

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

Код работает, выбирая случайное число между 0 и длиной массива, затем возвращая элемент в этот индекс.

Ответ 13

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

В Faker.js есть много утилит для генерации случайных тестовых данных. Это хороший вариант в контексте набора тестов:

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

Как отметили комментаторы, вы вообще не должны использовать эту библиотеку в рабочем коде.

Ответ 15

Простая функция:

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

Ответ 16

Я нашел способ избежать сложных ответов, просто объединив переменную 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>

Ответ 17

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

Ответ 18

var items = Array("elm1","elm2","elm3","elm4",...);

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

Ответ 19

Общий способ получить случайный элемент (ы):

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

На мой взгляд, лучше, чем возиться с прототипами или объявлять его как раз вовремя, я предпочитаю подвергать его окну:

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)

Ответ 21

еще один простой метод:

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

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

Ответ 22

Вот пример того, как это сделать:

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

Ответ 23

Создайте одно случайное значение и перейдите к массиву

Пожалуйста, попробуйте следующий код.

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

Ответ 24

Эта работа для меня без каких-либо повторений.

var Random_Value = Pick_Random_Value([1,3,7,9]);

function Pick_Random_Value(IN_Array,Return_Length,Last_Pick_Random_Key)
{
    Return_Length        = Return_Length || 1;
    Last_Pick_Random_Key = Last_Pick_Random_Key || 'Last_Pick_Random_Key';
    if(IN_Array != undefined && IN_Array.length > 0)
    {
        var Copy_IN_Array = JSON.parse(JSON.stringify(IN_Array)); // For disable array refrance
        if((typeof window[Last_Pick_Random_Key] !== 'undefined') && (window[Last_Pick_Random_Key] !== false))
        {
            var Last_Pick_Random = window[Last_Pick_Random_Key];
            if(Copy_IN_Array[Last_Pick_Random] != undefined)
            {
                Copy_IN_Array.splice(Last_Pick_Random,1);
            }
        }

        var Random_Values = [];
        var Return_Value  = false;
        if(Copy_IN_Array.length > 0)
        {
            if(Return_Length === 1)
            {
                var Random_Key = Math.floor(Math.random() * Copy_IN_Array.length);
                Return_Value = Copy_IN_Array[Random_Key];
            }
            else
            {
                if(Copy_IN_Array.length >= Return_Length)
                {
                    do {
                        Random_Values[Random_Values.length] = Copy_IN_Array.splice( Math.floor(Math.random() * Copy_IN_Array.length), 1)[0];
                    } while (Random_Values.length < Return_Length);
                    Return_Value = Random_Values;
                }
                else
                {
                    do {
                      Random_Values[Random_Values.length] = Copy_IN_Array.splice( Math.floor(Math.random() * Copy_IN_Array.length), 1)[0];
                    } while (Random_Values.length < Return_Length);
                    Return_Value = Random_Values;
                }
            }

        }
        else
        {
            Return_Value = IN_Array[0];
        }

        window[Last_Pick_Random_Key] = IN_Array.indexOf(Return_Value);
        if(window[Last_Pick_Random_Key] === -1)
        {
            for (var i = 0; i < IN_Array.length; i++)
            {
                if (JSON.stringify(IN_Array[i]) === JSON.stringify(Return_Value))
                {
                    window[Last_Pick_Random_Key] = i;
                    break;
                }
            }
        }

        return Return_Value;
    }
    else
    {
        return false;
    }
}