
데이터를 받아서 배열로 저장한 후 무작위로 내용을 추출 할 수 있는 함수이다.
const data = [
"1. 바나나",
"2. 사과",
"3. 배",
];
function randomValueFromArray(array) {
const random = Math.floor(Math.random() * array.length);
return array[random];
}
let fruit = randomValueFromArray(data);
console.log(fruit);
// Math.floor() : 가장 큰 정수 값을 돌려준다.
// Math.random() : 0~1 까지의 난수 실수 값을 돌려준다.
실행 결과
> 2. 사과
> 2. 사과
> 1. 바나나
> 2. 사과
> 3. 배
배열에 저장 된 순서와 상관 없이 배열의 [0]~[2]의 내용이 무작위로 선택된다.