반복문에서의 for in 정보
반복문에서의 for in
본문
예를 들어서...포문을 쓸 경우 보통 아래와 같은 식으로 작성합니다.
<script>
winner=["우루과이","이탈리아","독일","브라질","잉글랜드","아르헨티나","프랑스","스페인"];
for(i=0;i<winner.length;i++) winner[i]=winner[i]+' - '+(i+1)+'번째 월드컵 우승국';
document.write(winner.join('<BR>'));
</script>
winner=["우루과이","이탈리아","독일","브라질","잉글랜드","아르헨티나","프랑스","스페인"];
for(i=0;i<winner.length;i++) winner[i]=winner[i]+' - '+(i+1)+'번째 월드컵 우승국';
document.write(winner.join('<BR>'));
</script>
----------
우루과이 - 1번째 월드컵 우승국
이탈리아 - 2번째 월드컵 우승국
독일 - 3번째 월드컵 우승국
브라질 - 4번째 월드컵 우승국
잉글랜드 - 5번째 월드컵 우승국
아르헨티나 - 6번째 월드컵 우승국
프랑스 - 7번째 월드컵 우승국
스페인 - 8번째 월드컵 우승국
이탈리아 - 2번째 월드컵 우승국
독일 - 3번째 월드컵 우승국
브라질 - 4번째 월드컵 우승국
잉글랜드 - 5번째 월드컵 우승국
아르헨티나 - 6번째 월드컵 우승국
프랑스 - 7번째 월드컵 우승국
스페인 - 8번째 월드컵 우승국
그런데 for in 을 쓰면 일이 조금 더 쉬워집니다.
<script>
winner=["우루과이","이탈리아","독일","브라질","잉글랜드","아르헨티나","프랑스","스페인"];
for(i in winner) winner[i]=winner[i]+' - '+(Number(i)+1)+'번째 월드컵 우승국';
document.write(winner.join('<BR>'));
</script>
winner=["우루과이","이탈리아","독일","브라질","잉글랜드","아르헨티나","프랑스","스페인"];
for(i in winner) winner[i]=winner[i]+' - '+(Number(i)+1)+'번째 월드컵 우승국';
document.write(winner.join('<BR>'));
</script>
단 여기에는 주의 사항이 있습니다.
i 의 범위를 정해주면 i 를 "숫자"로 인식하지만 for in 으로 i 를 주면 "문자"로 인식한다는 점입니다.
<script>
winner=["우루과이","이탈리아","독일","브라질","잉글랜드","아르헨티나","프랑스","스페인"];
for(i=0;i<winner.length;i++); alert('i = ' +typeof i);
for(i in winner); alert('i = ' +typeof i);
</script>
winner=["우루과이","이탈리아","독일","브라질","잉글랜드","아르헨티나","프랑스","스페인"];
for(i=0;i<winner.length;i++); alert('i = ' +typeof i);
for(i in winner); alert('i = ' +typeof i);
</script>
그래서 포인으로 주고 계산을 할 경우는 Number() 나 parseInt() 로 한번 감아주는 것이 요령입니다.
추천
3
3
댓글 1개
감사