자바스크립트 자료형

박은정·2021년 7월 7일
0
post-thumbnail

배열

  • 형태 : 대괄호로 둘러싼다
    var lotto = [1,2,3,4,5,6];

  • 인덱스 0 값
    배열 lotto의 첫번째 값 lotto[0] == 1

  • 배열에 마지막 값으로 "7" 추가 lotto.push(7)

  • 배열에 랜덤숫자를 하나씩 추가를 해서
    총 6개의 랜덤숫자를 뽑았다.

배열을 이용한 랜덤숫자 6개추가

var lotto = [1,2,3,4,5,6];
document.write(lotto[0]);
lotto.push(7);
document.write(lotto); // 1,2,3,4,5,6,7

document.write("==정답==");
var lotto = [];
lotto.push(parseInt(Math.random() * 45 + 1));
lotto.push(parseInt(Math.random() * 45 + 1));
lotto.push(parseInt(Math.random() * 45 + 1));
lotto.push(parseInt(Math.random() * 45 + 1));
lotto.push(parseInt(Math.random() * 45 + 1));
lotto.push(parseInt(Math.random() * 45 + 1));
document.write(lotto);

나의 오답

나는 처음에 이런식으로 만들었는데 생각보다 잘 되지는 않았다.

var lotto2 = [];

var num = Math.random() * 44 + 1;
var boll = parseInt(num);
lotto2.push(boll);    

num = Math.random() * 44 + 1;
boll = parseInt(num);
lotto2.push(boll);  

num = Math.random() * 44 + 1;
boll = parseInt(num);
lotto2.push(boll);  

num = Math.random() * 44 + 1;
boll = parseInt(num);
lotto2.push(boll);

num = Math.random() * 44 + 1;
boll = parseInt(num);
lotto2.push(boll);  

num = Math.random() * 44 + 1;
boll = parseInt(num);
lotto2.push(boll); 
profile
새로운 것을 도전하고 배운것을 정리하려 합니다.

0개의 댓글

관련 채용 정보