iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0

https://ithelp.ithome.com.tw/upload/images/20240807/20144113XqcLlgnYBk.png

主題

利用 Fetch API、非同步載入的方式,並配合正規表達式處理字串,實現使用者輸入的城市名稱時動態地查找相對應的資料。

成果

完整程式碼
Demo效果

實作重點

Javascript

  1. 接資料

    1. 建立一個變數,預設是陣列

      const cities = [];
      
    2. 使用 Fetch 取得 json 資料

      fetch(endpoint)
        .then(blob => blob.json())
      
    3. 使用 淺拷貝 (MDN) 將接收的資料 pushcities 變數中

      
        .then(data => cities.push(...data));// (...data) ES6 淺拷貝
      
  2. 建立 function findMatches 專門來找查找字與城市的關聯,之後再調用它

    function findMatches(wordToMatch, cities) {
      return cities.filter(place => {
        const regex = new RegExp(wordToMatch, 'gi'); // g -> 全部, i -> 不分大小寫
        return place.city.match(regex) || place.state.match(regex)
      });
    }
    
  3. 建立 function numberWithCommas ,使用正規表達式將字串轉換成有逗點的數字,以增加數字的可讀性。Ex: 將數字 1234567 轉換為 1,234,567。

    function numberWithCommas(x) {
      return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
    
  4. 處理 input 輸入的資訊並顯示資料

    1. 綁定事件 changekeyup

      searchInput.addEventListener('change', inputHandler);
      searchInput.addEventListener('keyup', inputHandler); 
      
    2. 事件觸發時的邏輯

      1. 製作上面的 callback inputHandler

        function inputHandler() {}
        
      2. 當使用者打字進去就會調用 findMatches

        const matchArray = findMatches(this.value, cities);
        
      3. 渲染到 html :使用 map 跑 place,有相同的地區或城市時,用 replace 去替換值

        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>`);
        })
        
      4. 將這個 inputHandler 使用 樣板字串 把字呈現,並且在數字的地方調用 numberWithCommas

        return `
        <li>
          <span class="name">${cityName}, ${stateName}</span>
          <span class="population">${numberWithCommas(place.population)}</span>
        </li>
        `;
        
      5. join 去連接每個資訊

        const html = matchArray.map(place => {
        	...    
        }).join('');
        
      6. 將生成的 HTML 字串插入到 suggestions 元素中,以顯示搜尋結果

        suggestions.innerHTML = html;
        

額外知識

  • 正則表達式學習資訊

  • Fetch 與 Axios

    Fetch ( MDN )

    • Fetch 為內建 API ,無需額外安裝。
    • 用法較為簡單,但多個請求或請求終止時,要額外處理。

    Axios (GitHub)

    • Axios 是常用的第三方 HTTP 客戶端庫,需要額外安裝。
    • 功能強大,可以解決 Fetch 較難處理的部分。

上一篇
【Day06】05 - Flex Panel Gallery
系列文
AI 時代,基礎要有:JavaScript30 打下紮實基礎7
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言