JavaScript 배열에서 임의 값 가져오기

고려사항:

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

JavaScript를 사용하여 이 어레이에서 랜덤 값을 선택하려면 어떻게 해야 합니까?



질문에 대한 답변



간단한 원라이너입니다.

const randomElement = array[Math.floor(Math.random() * array.length)]; 

예를 들어 다음과 같습니다.

const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length); console.log(random, months[random]);




프로젝트에 언더스코어 또는 로다시가 이미 포함되어 있는 경우 를 사용할 수 있습니다.

// 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의 방법을 사용합니다.

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



메서드를 작성하기 위해 어레이 프로토타입에 함수를 정의하는 것을 고려할 수 있습니다.[].sample()랜덤 요소를 반환합니다.

먼저, 프로토타입 함수를 정의하려면 다음 스니펫을 코드에 넣습니다.

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

나중에 어레이에서 랜덤 요소를 샘플링하려면.sample():

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

이 코드 스니펫을 CC0 1.0 라이선스의 조건에 따라 퍼블릭도메인에 공개합니다.




~~보다 훨씬 빠르다Math.Floor()UI 요소를 사용하여 출력을 생성하면서 성능 최적화를 할 경우,~~게임에서 이깁니다.상세 정보

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

그러나 어레이에 수백만 개의 요소가 있다는 것을 알고 있다면 Bitwise Operator와Math.Floor()비트 연산자가 큰 숫자에 대해 이상하게 동작하기 때문입니다.출력에 대해서는, 다음의 예를 참조해 주세요.

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



최단 버전:

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