# 배열

## 배열

배열은 여러개의 데이터를 순차적으로 저장하는 저장소입니다.

```javascript
var 변수명 = [값1 , 값2 , 값3 ..........] 
```

### 배열

```javascript
let arr1 = new Array();
arr1[0] = 100;
arr1[1] = 200;

document.write(arr1[0],"<br>"); // 100
document.write(arr1[1],"<br>"); // 200
```

### &#x20;배열을 선언과 동시에 초기화

```javascript
let arr2 = new Array(100,200,300);

document.write(arr2[0],"<br>");     // 100
document.write(arr2[1],"<br>");     // 200
document.write(arr2[2],"<br><br>"); // 300
```

### 배열을 선언하지 않고 초기화

```javascript
let arr3 = [100, 200, 300];

document.write(arr3[0],"<br>");     // 100
document.write(arr3[1],"<br>");     // 200
document.write(arr3[2],"<br><br>"); // 300
```

### 배열 크기

```javascript
let arr4 = [100,200,300,400,500];

document.write(arr4.length);   // 5
```

### 배열 가져오기

```javascript
let arr1 = [100,200,300,400,500,600,700,800,900];
/*
document.write(arr1[0],"<br>");
document.write(arr1[1],"<br>");
document.write(arr1[2],"<br>");
document.write(arr1[4],"<br>");
document.write(arr1[5],"<br>");
document.write(arr1[6],"<br>");
document.write(arr1[7],"<br>");
document.write(arr1[8],"<br>");
*/
for(let i=0; i<=8; i++ ){
    document.write(arr1[i] + "<br>");
}
```

### 배열의 합구하기

```javascript
let arr2 = [100,200,300,400,500];
let sum = 0;

for(let i = 0; i<arr2.length; i++){
    //arr2[0] = 100
    //arr2[1] = 200
    //arr2[2] = 300
    //arr2[3] = 400
    //arr2[4] = 500
    sum += arr2[i]  //sum = sum + arr2[i}
    
}
document.write(sum);    // 1500
```

### forEach 사용하기

```javascript
const arr3 = [100,200,300,400,500,600,700,800,900];

arr3.forEach((element, index, array) => {
    document.write(element,"<br>");
    document.write(index,"<br>");
    document.write(array,"<br>");
});
```

### for in 문

```javascript
const arr3 = [100,200,300,400,500,600,700,800,900];
for( let i in arr3){
    document.write(arr3[i]);
}
```

### for of 문

```javascript
const arr3 = [100,200,300,400,500,600,700,800,900];
for( let i of arr3){
    document.write(i);
}
```

### 배열 비구조화 할당

```javascript
let [x, y] = [100, 200];

document.write(x); // 100
document.write(y); // 200
document.write("<br><br>");

[x, y] = [y, x]

document.write(x); // 200
document.write(y); // 100
```
