repetir para numeros numero matriz imprimir generar entre entero codigo aleatorios aleatorio aleatoria javascript

para - Obtener un valor aleatorio de una matriz de JavaScript



numero aleatorio javascript sin repetir (23)

Método de prototipo

Si planea obtener mucho un valor aleatorio, es posible que desee definir una función para él.

Primero, ponga esto en su código en algún lugar:

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

Ahora:

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

Código liberado en el dominio público bajo los términos de la licencia CC0 1.0 .

Considerar:

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

¿Cómo puedo seleccionar un valor aleatorio de esta matriz utilizando JavaScript?


Aquí hay un ejemplo de cómo hacerlo:

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


Crear un valor aleatorio y pasar a la matriz

Por favor intente el siguiente código ...

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


Digamos que desea elegir un elemento aleatorio que sea diferente de la última vez (no es realmente aleatorio, pero sigue siendo un requisito común) ...

Sobre la base de la respuesta de @Markus, podemos agregar otra función prototipo:

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

Y poner en práctica como tal:

var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement)


Edición de prototipo de matriz puede ser perjudicial. Aquí es una función simple para hacer el trabajo.

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 }

Uso:

// Example 1 var item = getArrayRandomElement([''January'', ''February'', ''March'']); // Example 2 var myArray = [''January'', ''February'', ''March'']; var item = getArrayRandomElement(myArray);


En mi opinión, mejor que jugar con los prototipos o declararlo justo a tiempo, prefiero exponerlo a la ventana:

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

Ahora en cualquier parte de tu aplicación la llamas así:

var rand = window.choice.call(array)

De esta manera usted puede seguir utilizando el bucle for(x in array) correctamente.


Esto es similar a, pero más general que, la solución de @Jacob Relkin:

Esto es ES2015:

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

El código funciona al seleccionar un número aleatorio entre 0 y la longitud de la matriz, y luego devolver el elemento a ese índice.


Esto funciona como un encanto para mí sin ninguna repetición.

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


Función recursiva, independiente que puede devolver cualquier número de elementos (idéntico a 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]) }


Función simple:

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

O

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

O

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


He encontrado una forma de evitar las complicaciones de la parte superior de la respuesta, simplemente concatenando la variable rand a otra variable que permita que ese número se muestre dentro de la llamada de myArray [] ;. Al eliminar la nueva matriz creada y jugar con sus complicaciones, he encontrado una solución funcional:

<!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>


La versión más corta:

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


Me ha resultado aún más sencillo agregar una función de prototipo a la clase Array:

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

Ahora puedo obtener un elemento de matriz aleatoria simplemente escribiendo:

var myRandomElement = myArray.randomElement()

Tenga en cuenta que esto agregará una propiedad a todas las matrices, por lo tanto, si está haciendo un bucle sobre uno usando for..in debería usar .hasOwnProperty() :

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

(Eso puede o no ser una molestia para usted).


Si desea escribirlo en una línea, como la solución de Pascual, otra solución sería escribirlo usando la función de búsqueda de ES6 (según el hecho, que la probabilidad de seleccionar al azar uno de los n elementos es 1/n ):

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

Utilice ese enfoque para propósitos de prueba y si hay una buena razón para no guardar la matriz solo en una variable separada. De lo contrario, las otras respuestas ( floor(random()*length y el uso de una función separada) son su camino a seguir.


Si tiene valores fijos (como una lista de nombres de mes) y desea una solución de una línea

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

La segunda parte de la matriz es una operación de acceso como se describe en ¿Por qué [5,6,8,7] [1,2] = 8 en JavaScript?


Si ya has incluido un underscore o logash en tu proyecto, puedes usar _.sample .

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

Si necesita obtener más de un elemento al azar, puede pasarlo como segundo argumento en el subrayado:

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

o use el método _.sampleSize en lodash:

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


Una forma genérica de obtener elementos aleatorios:

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


Utilizando Faker.js :

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


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

o versión más corta equivalente:

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

Código de muestra:

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


~~ es mucho más rápido que Math.Floor() , por lo que, cuando se trata de la optimización del rendimiento y la producción de elementos de la interfaz de usuario, ~~ gana el juego. MÁS INFORMACIÓN

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

Pero si sabe que la matriz tendrá millones de elementos de los que querría reconsiderar entre Bitwise Operator y Math.Floor() , ya que el operador bitwise se comporta de forma extraña con grandes números. Vea a continuación el ejemplo explicado con la salida. MÁS INFORMACIÓN

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


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

Establece una variable constante en la matriz, luego tiene otra constante que elige aleatoriamente entre los tres objetos en la matriz y la función simplemente devuelve los resultados.


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


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