[JavaScript 3] 반복문과 배열
배열
<!--ex6.html-->
<script>
var coworkers = ["egoing", "leezche"];
document.write(coworkers[0]);
document.write(coworkers[1]);
coworkers.push('duru');
coworkers.push('taeho');
document.write(coworkers.length);
</script>
<!--출력:
egoingleezche4
-->
변수(var) coworkers에 대괄호로 배열(array)임을 선언하고 두 개의 element를 넣는다.
push 메소드는 배열의 끝에 원소를 삽입하므로 coworkers = [“egoing”, “leezche”, “duru”, “taeho”]가 되며 길이는 4로 늘어난다.
반복문
<!--ex7.html-->
<ul>
<script>
document.write('<li>1</li>');
var i = 0;
while (i < 3) {
document.write('<li>2</li>');
document.write('<li>3</li>');
i = i + 1;
}
document.write('<li>4</li>');
</script>
</ul>
<!--출력:
1 2 3 2 3 2 3 4
-->
while 반복문을 통해 list를 작성할 수 있다. 이 경우 unordered list이므로 순번없이 번호가 쭉 목록으로 만들어진다.
버튼 개선
이전 포스팅에서 조건문과 토글을 통해 만든 버튼을 반복문과 배열을 통해 개선해보자
// 토글 코드 개선3: 반복문과 배열
<input type="button" value="night" onclick="
var target = document.querySelector('body');
if (this.value === 'night') {
target.style.backgroundColor = 'black';
target.style.color = 'white';
this.value = 'day';
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length) {
alist[i].style.color = 'powderblue';
console.log(alist[i]);
i = i + 1;
}
} else {
target.style.backgroundColor = 'white';
target.style.color = 'black';
this.value = 'night';
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length) {
alist[i].style.color = 'blue';
console.log(alist[i]);
i = i + 1;
}
}
">
이제 backgroundColor가 black일 때는 링크는 powderblue 색으로 나온다!
white일 때는 blue색으로 지정하는 것도 잊지 않고 넣어두자.
출처: [생활코딩!HTML+CSS+자바스크립트 JS편 Chapter 19~23]