Рандомный элемент массива javascript

Getting a random value from a JavaScript array

Ahh, I’ve learned something new. I was discussing the case where it equals EXACTLY 1, but apparently (according to W3Schools) Math.random is between 0 inclusive and 1 exclusive. My bad.

I might be wrong, but I recall var rand = myArray[Math.random() * myArray.length>>0] being slightly faster

Be aware that this function returns undefined as soon as you pass an empty array. It might be helpful to throw an exception in that case.

If you’ve already got underscore or lodash included in your project you can use _.sample .

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

If you need to get more than one item randomly, you can pass that as a second argument in underscore:

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

or use the _.sampleSize method in lodash:

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

When using typescript: Be aware that the return type would be «string | undefined» instead of «string» given a string array.

You may consider defining a function on the Array prototype, in order to create a method [].sample() which returns a random element.

First, to define the prototype function, place this snippet in your code:

Array.prototype.sample = function()

Later, to sample a random element from the array, just call .sample() :

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

I’m releasing these code snippets into the public domain, under the terms of the CC0 1.0 license.

Extending native object types should be avoided. I have deleted my answer, seeing it was upvoted a lot, but promoting bad practice. For more discussion on this issue see e.g. stackoverflow.com/questions/14034180/… and eslint.org/docs/rules/no-extend-native

@MarkusAmaltheaMagnuson That’s a good point. However, defining custom methods on prototypes isn’t necessarily an issue, especially if done so sparingly and outside of library code. The prototype provides an alternative solution that is quite pretty (in my subjective opinion) and exposes sometimes-overlooked but interesting parts of the language, at least when used sparingly. For nearly all application code, this won’t cause issues, so it comes down to a matter of taste.

~~ is much faster than Math.Floor() , so when it comes to performance optimization while producing output using UI elements, ~~ wins the game. MORE INFO

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

But if you know that the array is going to have millions of elements then you might want to reconsider between Bitwise Operator and Math.Floor() , as bitwise operators behave weirdly with large numbers. See below example explained with the output.

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

using «bitwise not» operator, while faster, is not that readable, so you have to choose what is more important to you

Читайте также:  Refresh page with php

For those who want to understand what it means, ~ is a bitwise not , which reverses the 1 s and 0 s in a binary number. As with all bitwise operators, it first converts the number into a 32 bit integer, which all you really want. Using ~~ restores the original as a 32-bit integer.

As for Math.floor() , All functions have an overhead which includes storing and restoring the original state. Generally, optimising compilers will look for opportunities to copy the code in place to avoid that overhead, but, with a dynamic language such as JavaScript, it’s harder to predict.

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

@KenSharp | 0 itself is a bitwise operation that does nothing, but in javascript floats are converted to ints before any bitwise operation. So it’s something like how + » doesn’t really do anything but can be used to convert things to strings.

It’s not the same as Math.floor but it is the correct thing to do here. It’s an operator so it’s faster than Math.floor if only because at any time while running some code can do Math.floor = someOtherFunction and they can’t do the same for ‘|’. On the other hand as for Math.floor and | being different try Math.floor(-1.5) vs -1.5 | 0 . By the way you don’t need the parentheses. | has a very low precedence.

Say you want to choose a random item that is different from the last time (not really random, but still a common requirement).

/** * Return a random element from an array that is * different than `last` (as long as the array has > 1 items). * Return null if the array is empty. */ function getRandomDifferent(arr, last = undefined) < if (arr.length === 0) < return null; >else if (arr.length === 1) < return arr[0]; >else < let num = 0; do < num = Math.floor(Math.random() * arr.length); >while (arr[num] === last); return arr[num]; > > 
const arr = [1,2,3]; const r1 = getRandomDifferent(arr); const r2 = getRandomDifferent(arr, r1); // r2 is different than r1. 

If you have fixed values (like a month name list) and want a one-line solution

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

The second part of the array is an access operation as described in Why does [5,6,8,7][1,2] = 8 in JavaScript?

Such code is a bad and harmful practice. It should never be used in production. It has low readability and it has a hardcoded array length. The person changing the array input may forget to edit the length hardcoded in the end.

@Seagull OP never asked for an specific environment. Also this comment is meaningless as it could be applied to almost all the answers in this question 😉

But most people arrive to this question from Google search and the may use the solution in other scenarios than original OP.

Читайте также:  How to add element in arraylist in java

I fully agree, having to hardcode the array length this way is simply very bad coding, asking for maintenance issues.

If you want to write it on one line, like Pascual’s solution, another solution would be to write it using ES6’s find function (based on the fact, that the probability of randomly selecting one out of n items is 1/n ):

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

Use that approach for testing purposes and if there is a good reason to not save the array in a seperate variable only. Otherwise the other answers ( floor(random()*length and using a seperate function) are your way to go.

Many of the offered solutions add a method to a specific Array which restricts it's use to just that array. This solution is reusable code that works for any array and can be made type safe.

TypeScript

export function randChoice(arr: Array): T

JavaScript

Editing Array prototype can be harmful. Here it is a simple function to do the job.

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

If you need to fetch a random item more than once, then, obviously you would use a function. One way is to make that function a method of the Array.prototype , but that will normally get you shouted down for tampering with built in prototypes.

However, you can add the method to the specific array itself:

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

That way you can use months.random() as often as you like without interfering with the generic Array.prototype .

As with any random function, you run the risk of getting the same value successively. If you don’t want that, you will need to track the previous value with another property:

If you’re going to do this sort of thing often, and you don’t want to tamper with Array.prototype , you can do something like this:

function randomValue() < return this[Math.floor(Math.random()*this.length)]; >var data = [ … ]; var moreData = [ … ]; data.random=randomValue; moreData.random=randomValue; 

Источник

Как выбрать случайный элемент из массива js

Чтобы выбрать случайный элемент из массива можно воспользоваться методами Math.random() и Math.floor() :

Выбрать случайный элемент массива можно не только с помощью стандартных возможностей языка.
Давайте обратимся к библиотеке Lodash, там есть именно то, что нам нужно.

const movies = [ 'Star Wars', 'Pirates of the Caribbean', 'Lord of the Rings', 'Avengers', 'The Dark Fields', ]; //выбираем фильм на вечер с помощью метода _.sample() const random = _.sample(movies); console.log("Random:", random); // => Random: Pirates of the caribbean 

Познакомились с методом _.sample() и выбрали фильм на вечер.

Читайте также:  How to get class name python

Источник

JavaScript выбирает случайное значение из массива

JavaScript выбирает случайное значение из массива

В этом руководстве будет обсуждаться, как выбрать случайное значение из массива с помощью функции Math.random() в JavaScript.

Выберите случайное значение из массива с помощью функции Math.random() в JavaScript

Мы можем выбрать значение из заданного массива, используя его индекс в JavaScript. Чтобы выбрать случайное значение из данного массива, нам нужно сгенерировать случайный индекс в диапазоне от 0 до длины массива. Мы можем сгенерировать случайное значение, используя функцию Math.random() , и чтобы установить диапазон этого случайного значения, мы должны умножить его на длину массива, которую мы можем получить с помощью функции length .

Случайное значение, генерируемое функцией Math.random() , является значением с плавающей запятой. Чтобы преобразовать значение с плавающей запятой в целое число, мы должны использовать функцию Math.floor() . Функция Math.floor() преобразует число с плавающей запятой в целое число, которое будет меньше заданного числа. Например, давайте создадим массив из пяти значений, выберем из него одно случайное значение и покажем его на консоли. См. Код ниже.

var myArray = ['one', 'two', 'three', 'four', 'five']; var rand = Math.floor(Math.random()*myArray.length); var rValue = myArray[rand]; console.log(rValue) 

В приведенном выше коде случайный индекс будет храниться в переменной rand , и с помощью этого индекса мы можем выбрать случайное значение из массива, которое будет сохранено в переменной rValue . Вы также можете использовать побитовый оператор НЕ ~~ или побитовый ИЛИ | вместо функции Math.floor() для преобразования числа с плавающей запятой в целое число. Использование побитовых операторов быстрее, но может не работать для массива, содержащего миллионы значений. Например, сгенерируем случайное число с помощью побитового оператора НЕ . См. Код ниже.

var myArray = ['one', 'two', 'three', 'four', 'five']; var rand = ~~(Math.random()*myArray.length); var rValue = myArray[rand]; console.log(rValue) 

Теперь сгенерируем случайное число с помощью побитового оператора ИЛИ . См. Код ниже.

var myArray = ['one', 'two', 'three', 'four', 'five']; var rand = Math.random()*myArray.length | 0; var rValue = myArray[rand]; console.log(rValue) 

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

function RandArray(array)  var rand = Math.random()*array.length | 0;  var rValue = array[rand];  return rValue; > var myArray = ['one', 'two', 'three', 'four', 'five', 'six']; var rValue = RandArray(myArray); console.log(rValue) 

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

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

Сопутствующая статья - JavaScript Array

Источник

Оцените статью