2017-12-09 1 views

답변

0

for 루프를 사용하십시오.

이 시도 :

var crystalValues = []; 

for(var i = 0;i < 4;i++){ 
    crystalValues.push(Math.floor(Math.random()*12+1)) 
} 

console.log(crystalValues); 
+0

이 숫자가 서로 같지 않게하려면 어떻게해야합니까? –

1

함수는 다음 랜덤 int 배열을 생성한다. 많은 사람들이, minmax이 최소 및 최대 임의 값

function createRandomArray(count,min,max){ 
 
     const rand =() => Math.floor(Math.random() * (max - min) + min); 
 
     const vals = []; 
 
     while(count-- > 0){ vals.push(rand()) } 
 
     return vals; 
 
    } 
 
    console.log(createRandomArray(4,1,13)); 
 
    
 

const crystalValues = []; 
crystalValues.push(...createRandomArray(4,1,13)) 

또는를 다음과 같이 다른 배열에 할당 할 수 있습니다를 설정하는 방법

count 세트 그냥 직접 할당하십시오

이 기능을 입력하는 시간을 절약하려는 경우
const crystalValues = createRandomArray(4,1,13); 
0

당신은 단순히 트릭을 할 것 루프 Array.from()

var gen =() => { 
 
\t return Array.from({length: 4},() => Math.floor(Math.floor(Math.random()*12+1))); 
 
} 
 

 
console.log(gen());

+0

이 숫자가 서로 동일하지 않게하려면 어떻게해야합니까? –

0

를 사용할 수 있습니다.

random4() { 
    var crystalValues = []; 
    for (var i=0; i < 4 ; i++) { 
     randomNumber = Math.floor(Math.random()*12+1); 
     while (crystalValues.indexOf(randomNumber) !== -1) { 
      randomNumber = Math.floor(Math.random()*12+1); 
     } 
     crystalValues[i] = randomNumber; 
    } 
    return crystalValues; 
} 
+0

이 숫자가 서로 결코 같지 않게하려면 어떻게해야합니까? –

+0

나는 당신에게 보여줄 나의 코드를 편집했다 : 당신이 유일한 하나를 얻을 때까지 새로운 난수의 색인을 점검하면서 while 루프를 추가한다. 코드를 변경하면 무한 루프로 끝나지 않게하십시오. –

관련 문제