type ahead

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);

fetch()

  1. 서버에게 어떤파일을 응답하라고 요청하는것이다.

  2. 비동기로 이루어지기때문에 fetch 되는 동안 다른 코드를 실행한다.

  3. 그 작업이 끝나고나서 콜백함수를 실행시켜주는것을 👉 then()이라고한다.

  4. response 객체 가 들어게 되는데 여기 안에는 서버가 응답한 결과값있다.

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

.push

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);

findMatches()

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개가 필요함 하나는 검색한 단어, 하나는 전체 배열

  • RegExp 👉 객체는 리터럴 표기법과 생성자로써 생성할

  • 리터럴 표기법 매개변수는 두 빗금으로 감싸야 하며 따옴표를 사용하지 않는다.

  • 생성자 함수의 매개변수는 빗금으로 감싸지 않으나 따옴표를 사용합니다.

  • gi 👉 global match와 ignore case를 뜻함

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

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);
}

Last updated

Was this helpful?