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()
서버에게 어떤파일을 응답하라고 요청하는것이다.
비동기로 이루어지기때문에 fetch 되는 동안 다른 코드를 실행한다.
그 작업이 끝나고나서 콜백함수를 실행시켜주는것을 👉 then()이라고한다.
response 객체 가 들어게 되는데 여기 안에는 서버가 응답한 결과값이 있다.

.push

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

Last updated
Was this helpful?