JavaScript 배열에서 임의의 값 가져 오기
중히 여기다:
var myArray = ['January', 'February', 'March'];
JavaScript를 사용하여이 배열에서 임의의 값을 어떻게 선택할 수 있습니까?
var rand = myArray[Math.floor(Math.random() * myArray.length)];
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)) {
...
}
}
(이는 번거로울 수도 있고 아닐 수도 있습니다.)
프로젝트에 이미 밑줄 이나 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);
프로토 타입 방법
임의의 값을 많이 얻을 계획이라면 이에 대한 함수를 정의 할 수 있습니다.
먼저 코드에 어딘가에 넣으십시오.
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
지금:
[1,2,3,4].sample() //=> a random element
CC0 1.0 라이센스 조건에 따라 공개 도메인에 공개 된 코드 .
지난번과 다른 무작위 항목을 선택하고 싶다고 가정 해 보겠습니다 (정말 무작위가 아니지만 여전히 일반적인 요구 사항).
@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)
~~
는보다 훨씬 빠르기 Math.Floor()
때문에 UI 요소를 사용하여 출력을 생성하는 동안 성능 최적화와 관련 ~~
하여 게임 에서 승리합니다. 더 많은 정보
var rand = myArray[~~(Math.random() * myArray.length)];
그러나 배열에 수백만 개의 요소가 있다는 것을 알고 있다면 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]
고정 값 (예 : 월 이름 목록)이 있고 한 줄 솔루션을 원하는 경우
var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]
배열의 두 번째 부분은 JavaScript에서 [5,6,8,7] [1,2] = 8이 되는 이유에 설명 된 액세스 작업입니다 .
어레이 프로토 타입을 편집하면 해로울 수 있습니다. 여기에 작업을 수행하는 간단한 기능이 있습니다.
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);
Pascual의 솔루션과 같이 한 줄에 작성하려는 경우 다른 솔루션은 ES6의 찾기 기능을 사용하여 작성하는 것입니다 (사실에 따라 n
항목 중 하나를 무작위로 선택할 확률 이 1/n
).
var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));
console.log(item);
테스트 목적으로 그리고 배열을 별도의 변수에만 저장하지 않는 좋은 이유가있는 경우이 방법을 사용하십시오. 그렇지 않으면 다른 답변 ( floor(random()*length
및 별도의 기능 사용)이 갈 길입니다.
Faker.js has many utility functions for generating random test data. It is a good option in the context of a test suite:
const Faker = require('faker');
Faker.random.arrayElement(['January', 'February', 'March']);
As commenters have mentioned, you generally should not use this library in production code.
Recursive, standalone function which can return any number of items (identical to 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])
}
This is similar to, but more general than, @Jacob Relkin's solution:
This is ES2015:
const randomChoice = arr => {
const randIndex = Math.floor(Math.random() * arr.length);
return arr[randIndex];
};
The code works by selecting a random number between 0 and the length of the array, then returning the item at that index.
var item = myArray[Math.floor(Math.random()*myArray.length)];
or equivalent shorter version:
var item = myArray[(Math.random()*myArray.length)|0];
Sample code:
var myArray = ['January', 'February', 'March'];
var item = myArray[(Math.random()*myArray.length)|0];
console.log('item:', item);
Simple Function :
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();
I've found a way around the top answer's complications, just by concatenating the variable rand to another variable that allows that number to be displayed inside the calling of myArray[];. By deleting the new array created and toying around with it's complications, I've come up with a working solution:
<!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>
static generateMonth() {
const theDate = ['January', 'February', 'March'];
const randomNumber = Math.floor(Math.random()*3);
return theDate[randomNumber];
};
You set a constant variable to the array, you then have another constant that chooses randomly between the three objects in the array and then the function simply returns the results.
A generic way to get random element(s):
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;
}
To get crypto-strong random item form array use
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) )
In my opinion, better than messing around with prototypes , or declaring it just in time, I prefer exposing it to window:
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)];
}
Now anywhere on your app you call it like:
var rand = window.choice.call(array)
This way you can still use for(x in array)
loop properly
Here is an example of how to do it:
$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)];
another easy method :
var myArray = ['keke','keko','cano','halo','zirto'];
var randomValue = myArray[Math.round((Math.random()*1000))%myArray.length];
Create one random value and pass to array
Please try following code..
//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);
참고URL : https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array
'development' 카테고리의 다른 글
C #에서 public, private, protected 및 no access modifier의 차이점은 무엇입니까? (0) | 2020.09.30 |
---|---|
개체의 속성을 기반으로 개체 목록을 정렬하는 방법은 무엇입니까? (0) | 2020.09.30 |
Java로 새 목록을 만드는 방법 (0) | 2020.09.30 |
jQuery를 사용하여 이미지 소스 변경 (0) | 2020.09.30 |
HTML 페이지에서 스크롤 막대 숨기기 (0) | 2020.09.30 |