# type ahead

{% tabs %}
{% tab title="JAVASCRIPT" %}

```javascript
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

const cities = []; // 데이타값을 받음
fetch(endpoint)
  .then(blob => blob.json()) // 제이슨 
  .then(data => cities.push(...data)); // 데이터 
//json 내용 가져오기 
// fetch -> 클라이언트가 서버레 어떤파일을 응답해달라고 요청한것


function findMatches(wordToMatch, cities) {
  return cities.filter(place => {
    //도시나 주가 검색한 것과 일치하는지 확인후 일치하는 단어만 새 배열 만들기
    const regex = new RegExp(wordToMatch, 'gi');
    return place.city.match(regex) || place.state.match(regex)
  });
}

 // 숫자에 천 단위 콤마 표시
function numberWithCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// 일치하는 단어 보여주기
function displayMatches() {
  const matchArray = findMatches(this.value, cities);
  const html = matchArray.map(place => {
    const regex = new RegExp(this.value, 'gi');
    const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
    const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
    return `
      <li>
        <span class="name">${cityName}, ${stateName}</span>
        <span class="population">${numberWithCommas(place.population)}</span>
      </li>
    `;
  }).join('');
  suggestions.innerHTML = html;
}

// 이벤트 리스너 달기
const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');

searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);
```

{% endtab %}

{% tab title="HTML" %}

```markup
  <form class="search-form">
    <input type="text" class="search" placeholder="City or State">
    <ul class="suggestions">
      <li>Filter for a city</li>
      <li>or a state</li>
    </ul>
  </form>
```

{% endtab %}

{% tab title="" %}

```css
html {
  box-sizing: border-box;
  background: #ffc600;
  font-family: 'helvetica neue';
  font-size: 20px;
  font-weight: 200;
}

*, *:before, *:after {
  box-sizing: inherit;
}

input {
  width: 100%;
  padding: 20px;
}

.search-form {
  max-width: 400px;
  margin: 50px auto;
}

input.search {
  margin: 0;
  text-align: center;
  outline: 0;
  border: 10px solid #F7F7F7;
  width: 120%;
  left: -10%;
  position: relative;
  top: 10px;
  z-index: 2;
  border-radius: 5px;
  font-size: 40px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.12), inset 0 0 2px rgba(0, 0, 0, 0.19);
}

.suggestions {
  margin: 0;
  padding: 0;
  position: relative;
  /*perspective: 20px;*/
}

.suggestions li {
  background: white;
  list-style: none;
  border-bottom: 1px solid #D8D8D8;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.14);
  margin: 0;
  padding: 20px;
  transition: background 0.2s;
  display: flex;
  justify-content: space-between;
  text-transform: capitalize;
}

.suggestions li:nth-child(even) {
  transform: perspective(100px) rotateX(3deg) translateY(2px) scale(1.001);
  background: linear-gradient(to bottom,  #ffffff 0%,#EFEFEF 100%);
}

.suggestions li:nth-child(odd) {
  transform: perspective(100px) rotateX(-3deg) translateY(3px);
  background: linear-gradient(to top,  #ffffff 0%,#EFEFEF 100%);
}

span.population {
  font-size: 15px;
}

.hl {
  background: #ffc600;
}
```

{% endtab %}
{% endtabs %}

### fetch()

1. 서버에게 어떤파일을 응답하라고 요청하는것이다.
2. 비동기로 이루어지기때문에 **fetch 되는 동안** **다른 코드를 실행**한다.&#x20;
3. **그 작업이 끝나고나서** **콜백함수를 실행**시켜주는것을 :point\_right: **then()**&#xC774;라고한다.&#x20;
4. &#x20;**response 객체** 가 들어게 되는데 여기 안에는 서버가 **응답한 결과값**이 **있다.**

{% tabs %}
{% tab title="JAVASCRIPT" %}

```javascript
fetch(`member.json`).then(function (blob) {
  blob.json()
    .then(function (data) {
      console.log(data);
      console.log('hello');
  });
})
```

{% endtab %}

{% tab title="JSON" %}

```
[{
    "name": "boa",
    "age": "31"
  },
  {
    "name": "mori",
    "age": "26"
  },
  {
    "name": "hoon",
    "age": "39"
  },
  {
    "name": "haha",
    "age": "89"
  },
  {
    "name": "hoho",
    "age": "100"
  },
  {
    "name": "bobo",
    "age": "15"
  },
  {
    "name": "baba",
    "age": "2"
  }
]
```

{% endtab %}
{% endtabs %}

![](https://810537134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MZh1fxUzW3zjggiSfv4%2F-Mcy1THTYiZ9WAXe1uXK%2F-Mcy1_bIiTEP99i6lt54%2Fimage.png?alt=media\&token=1de3e4ad-0f35-46cd-b834-0de5b6d0454d)

###

### .push

```javascript
const parts = ['knoo', 'shoo'];
let lyrics = ['head', ...parts, 'and', 'toes']; //["head", "shoulders", "knees", "and", "toes"]

const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
arr1.push(...arr2); // 0 , 1, 2, 3, 4, 5 

console.log(lyrics);
console.log(arr1);
```

![](https://810537134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MZh1fxUzW3zjggiSfv4%2F-Mcy2TjLkXddJhK6Qk-1%2F-Mcy3lfcZ3_NB85O6kir%2Fimage.png?alt=media\&token=9eec3e2b-3682-41ba-8f98-bcd8b193672d)

###

### findMatches()&#x20;

```javascript
function findMatches(wordToMatch, cities) {
  return cities.filter(place => {
    const regex = new RegExp(wordToMatch, "gi");
    return place.city.match(regex) || place.state.match(regex);
    //  city와 state 두개 이기때문에 || 연산자 사용 
  });
}
```

* **findMatches() 인자 2개가 필요함 하나는 검색한 단어, 하나는 전체 배열**&#x20;
* **RegExp** :point\_right: 객체는 리터럴 표기법과 생성자로써 생성할&#x20;
* &#x20;**리터럴 표기법** 매개변수는 두 빗금으로 감싸야 하며 따옴표를 사용하지 않는다.&#x20;
* **생성자 함수**의 매개변수는 빗금으로 감싸지 않으나 따옴표를 사용합니다.
* **gi** :point\_right: global match와 ignore case를 뜻함

###

### 사용자 입력한 단어로 결과값 찾기

```javascript
function displayMatches(){
  console.log(this.value);
}
 
const searchInput = document.querySelector(".search");
const resultArea = document.querySelector(".result");
 
searchInput.addEventListener("change", displayMatches);
searchInput.addEventListener("keyup", displayMatches);

/*사용자가 input에 입력하는 값을 가져오고, findMatches() 결과를 보. 
input과 결과창을 셀렉팅하고, input에게 이벤트 리스너를 걸어준다.*/


function displayMatches() {
  const matchArray = findMatches(this.value, strArr); // this.value 와 배열이 
  console.log(matchArray);
}

```

![](https://810537134-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MZh1fxUzW3zjggiSfv4%2F-McyCTOMOgsNGFQySSvs%2F-McyC_UlqXqPGX-hEwOi%2Fimage.png?alt=media\&token=718a631f-7eb7-4d4c-b477-e88e1003cc72)
