Try   HackMD

Javascript Filter 迴圈 | 快速找到疫情國家排名 | Coronavirus Country Ranking

tags: JavaScript 2020/03/18

影片

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Big Boy Can Code

主題

https://www.worldometers.info/coronavirus/ 網站上並沒有排名,該如何使用JavaScript 的方法快速知道台灣現在排名

三種方法

  • 直接到上方目標網站,F12 打開 DevTools,在 Console 輸入其中一種就可以
// ----- Javascript foreach Array.from(document.querySelectorAll("tr")).forEach((row, index) => { if (row.cells[0].innerHTML.includes("Taiwan")) { console.log( index) } }) // ----- Javascript Map Array.from(document.querySelectorAll("tr")).map((row,index) => { if (row.cells[0].innerHTML.includes("Taiwan")) { return index } }) // ----- Javascript filter Array.from(document.querySelectorAll('tr')).filter(row =>{ if(row.cells[0].innerHTML.includes('Taiwan')){ return row } })[0].rowIndex

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

findIndex

let index = Array.from(document.querySelectorAll("tr")).findIndex(row => row.cells[0].innerText === "Taiwan") console.log(`台灣的排名是 : ${index}`)

Net Chen

`$` 反引號backticks

console.log(`台灣的排名是 : ${index}`) //相同於 console.log('台灣的排名是 :' + index)

想知道更多陣列處理技巧
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

![](https://i.imgur.com/zhzNVcv.png)
``