모든 언어에 있는 배열이지만...

 

가끔 그 사용법이 헷갈릴때가 있다. 특히 자바스크립트라면 더욱 그렇다...

 

그래서 오늘은 자바스크립트에서 배열을 이용하는 방법을 좀 더 면밀히 살펴보고자 한다...

 

HTML 코드이다...

 

<html>
<head>
<script type="text/javascript">
var country = [ "Korea", "Japan", "China", "US", "UK", "Indonesia", "Singapore", "Italy", "Canada", "Denmark" ];
document.write(country[0]);
document.write(country[1]);
document.write(country[2]);
document.write(country[3]);
document.write(country[4]);
document.write(country[5]);
document.write(country[6]);
document.write(country[7]);
document.write(country[8]);
document.write(country[9]);
</script>
</head>
<body>
</body>
</html>

 

결과를 보자...

 

KoreaJapanChinaUSUKIndonesiaSingaporeItalyCanadaDenmark

 

줄 바꿈이 안되어 있다? 처리하자...

 

<html>
<head>
<script type="text/javascript">
var country = [ "Korea", "Japan", "China", "US", "UK", "Indonesia", "Singapore", "Italy", "Canada", "Denmark" ];
document.write(country[0]+"<br>");
document.write(country[1]+"<br>");
document.write(country[2]+"<br>");
document.write(country[3]+"<br>");
document.write(country[4]+"<br>");
document.write(country[5]+"<br>");
document.write(country[6]+"<br>");
document.write(country[7]+"<br>");
document.write(country[8]+"<br>");
document.write(country[9]+"<br>");
</script>
</head>
<body>
</body>
</html>

 

하지만 코드가 썩 예쁘지 않다... for문으로 처리해볼까?

 

<html>
<head>
<script type="text/javascript">
var country = [ "Korea", "Japan", "China", "US", "UK", "Indonesia", "Singapore", "Italy", "Canada", "Denmark" ];

for(var i=0;i<country.length;i++)
        document.write(country[i]+"<br>");
</script>
</head>
<body>
</body>