> For the complete documentation index, see [llms.txt](https://leeans-dev-book.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leeans-dev-book.gitbook.io/docs/lecture/javascript/array-object.md).

# Array 와 Object

여러 데이터를 변수에 저장하려면 지금까지 배웠던 방식으로는 이렇게 해야한다.

```javascript
var car = '셀토스';
var carPrice = 2700;
var carColor = 'white';
```

세개만 해도 벌써 귀찮은데 만약 100개라면??

다행히 하나의 변수에 여러개의 데이터를 저장하는 방법이 있다.&#x20;

## Array 자료형

```javascript
var car = ['셀토스', 2700, 'white'];
    console.log(car);     //출력 결과  ['셀토스', 2700, 'white']
    console.log(car[0]);  //출력 결과  '셀토스'

    //데이터 변경
    car[0] = '페라리';
    console.log(car[0]);  //출력 결과 '페라리'
    
    //데이터 추가
    car[3] = '엉차';   
    console.log(car[3]);  //출력 결과 '엉차' 

```

## Object 자료형

```javascript
var car2 = {name:'셀토스', price:2700, color:'white'};
    console.log(car2['name']);  //출력결과 '셀토스'
    console.log(car2.price);    //출력결과 2700
    
    //데이터 변경
    car2.name = '포르쉐';
    //데이터 추가 
    car2.option = '엉차';
    console.log(car2.name, car2.option); //출력결과 '포르쉐' , '엉차'
    
```

Object는 key: value 형태로 여러 속성을 하나의 변수에 저장할 수 있도록 해주는 데이터 타입

Array 와 Object는 이렇게도 쓸 수 있다.

```javascript
var carCollection = [{name:'셀토스', price : 2700},
      {name:'포르쉐',price: 10000},
      {name:'람보르기니',price: 10000}]

var collection = {car : ['셀토스', 2700, 'white'],
               coin : ['대한민국', 50]}


    console.log(carCollection);
    console.log(collection);
```

<figure><img src="/files/JyAmMUpHcb5bu37WB1CO" alt=""><figcaption></figcaption></figure>

## Array와 Object 차이&#x20;

1. 데이터를 저장하고 뽑아서 사용할 때의 차이&#x20;

array는 저장 할 때에는 간단하지만 자료를 뽑아낼 때 불편하다.

```javascript
var car = ['셀토스', 2700, 'white', '엉차', '엉뜨', 'HUD', '전방추돌방지'];

var car2 = {name:'셀토스', price:2700, color:'white', option1: '엉차',
            option2: '엉뜨', option3: 'HUD',option4: '전방추돌방지'};
```

예를 들어 이런 Array와 Object가 있다고 한다면&#x20;

Array에서 색상을 뽑으려면 색상 데이터가 몇번째에 있었지를 생각해야하지만

Object에서는 color 키값만 기억하면 된다.&#x20;

2. 순서 개념&#x20;

array에는 순서 개념이 있고 object에는 없다.&#x20;

array 자료는 순서개념이 있다보니

* 가나다 순 정렬
* n번 자료부터 n1번 자료까지 자르기
* n번 자료 바꾸기
* 맨뒤나 맨 앞에 자료 넣기
* 원하는 자료가 들어있나 검색&#x20;

이런 것들을 할 수 있다.&#x20;

<figure><img src="/files/Gdqyv8hb0Zo27B11ZyTg" alt=""><figcaption><p>javascript array methods</p></figcaption></figure>

지금은 이런 것들이 있다라고 알고 필요할 때 검색해서 사용해보자.

{% embed url="<https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator>" %}

✨ 과제. js011.html에서 생성한 car2에 저장된 name과 price를 상품명과 가격 부분에 넣어보자.

{% code title="js011.html" %}

```html
<div class="container mt-3">
  <div class=" p-3">
    <span>상품명</span>
    <span>가격</span>
  </div>
</div>
```

{% endcode %}

carCollection이나 collection 처럼 복잡한 구조에 데이터는 어떻게 뽑을 수 있을까?&#x20;

<pre class="language-javascript"><code class="lang-javascript">var carCollection = [{name:'셀토스', price : 2700},
      {name:'포르쉐',price: 10000},
      {name:'람보르기니',price: 10000}]

    var collection = {car : ['셀토스', 2700, 'white']
                     ,coin : ['대한민국', 50]}

<strong>console.log(carCollection[0].name);  //출력 결과 '셀토스'
</strong>console.log(collection.coin[0]);     //출력 결과 '대한민국'
</code></pre>

지금까지 배운게 어디에 쓰이는가?&#x20;

쇼핑몰 사이트를 보면서 얘기해보자.

✨과제.  js013.html을 생성하고 아래의 코드를 붙여넣은 뒤 각 상품의 title 과 price를 html에 넣어서 완성해보자. (반복문 사용)

{% code title="js013.html" %}

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

</head>
<body>
    <div class="card-group container">
        <div class="card">
            <img src="https://via.placeholder.com/600">
            <div class="card-body">
                <h5>Card title</h5>
                <p>가격 : 70000</p>
                <button class="btn btn-danger">주문하기</button>
            </div>
        </div>
        <div class="card">
            <img src="https://via.placeholder.com/600">
            <div class="card-body">
                <h5>Card title</h5>
                <p>가격 : 70000</p>
                <button class="btn btn-danger">주문하기</button>
            </div>
        </div>
        <div class="card">
            <img src="https://via.placeholder.com/600">
            <div class="card-body">
                <h5>Card title</h5>
                <p>가격 : 70000</p>
                <button class="btn btn-danger">주문하기</button>
            </div>
        </div>
    </div>

    <script>
        var products = [
            { id : 0, price : 70000, title : 'Blossom Dress' },
            { id : 1, price : 50000, title : 'Springfield Shirt' },
            { id : 2, price : 60000, title : 'Black Monastery' }
        ];
    </script>
</body>
</html>
```

{% endcode %}

밑에 보고 따라치지 말고 혼자서 해보자

```javascript
 for(var i =0; i< products.length; i++){
            cardChange(i);
        }

function cardChange(num) {
    document.querySelectorAll('.card-body h5')[num].innerHTML = products[num].title;
    $('.card-body p').eq(num).html(products[num].price);
}
```

💎javascript 변수 활용&#x20;

자바 스크립트에선 덧셈기호로 문자를 연결할 수 있다.

```javascript
console.log(1+"3");      //'13' 출력 된다.
```

숫자 + 숫자는 덧셈&#x20;

숫자 + 문자는 숫자를 문자로 바꿔서 연결해준다.

```javascript
var a = '풀스택개발자';
console.log('문자' + a + '문자'); // '문자풀스택개발자문자' 출력된다.
```

이렇게 문자 사이에 변수를 넣어서 활용할 수 있다.

변수 양옆에 + 쓰는게 귀찮다면

```javascript
console.log(`문자 ${a} 문자`);// '문자 풀스택개발자 문자' 출력된다.
```

이렇게 백틱 기호 \`  사이에 문자열과 ${변수}를 사용하면 된다.

백틱기호는 숫자1 왼쪽키 \~ 밑에 있는 키다.&#x20;


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://leeans-dev-book.gitbook.io/docs/lecture/javascript/array-object.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
