選單
GSS 技術部落格
在這個園地裡我們將從技術、專案管理、客戶對談面和大家分享我們多年的經驗,希望大家不管是喜歡或是有意見,都可以回饋給我們,讓我們有機會和大家對話並一起成長!
若有任何問題請來信:gss_crm@gss.com.tw
2 分鐘閱讀時間 (343 個字)

前端小分享 在javascript裡多元使用 array part 2

前端小分享 在javascript裡多元使用 array part 2

以下介紹ES5和ES6+ Array的常見用法,也許能讓你寫出來的JS Code看起來更簡潔易懂

主要有八種:

  1. Array.forEach
  2. Array.map
  3. Array.find
  4. Array.findIndex
  5. Array.filter
  6. Array.every
  7. Array.some
  8. Array.reduce

這篇要來介紹Array.find &  Array.findIndex,接下來說明吧!


 3. Array.find

回傳 第一個 滿足條件的元素

Array.find(callback(element[, index[, array]])[, thisArg])  

範例: 

假設,有一員工的清單

const employees = [
{ name: "David Carlson", age: 30 },
{ name: "John Cena", age: 34 },
{ name: "Mike Sheridan", age: 25 },
{ name: "John Carte", age: 50 }]; 

那我們想取得一員工名字含有John的資料,這時我們就可以使用find:  

const employee = employees.find(function (employee) {
  return employee.name.indexOf('John') > -1;});

console.log(employee); // { name: "John Cena", age: 34 } 

 儘管還有一個叫做John Carte的員工,但find還是在找到第一個符合條件的就停止了,也就是John Cena,所以回傳的值為John Cena

 等同: 

const employees = [
{ name: "David Carlson", age: 30 },
{ name: "John Cena", age: 34 },
{ name: "Mike Sheridan", age: 25 },
{ name: "John Carte", age: 50 }];

let user;
for(let i = 0; i < employees.length; i++) {
  if(employees[i].name.indexOf('John') > -1) {
    user = employees[i];
    break;
  }}

console.log(user); // { name: "John Cena", age: 34 } 

可以看到,一般的loop的程式碼看起來更多較不易理解  

  使用find的好處:

  • 使用簡短的程式就能快速找到任何元素
  • 一找到符合條件的即停止,無須額外的break

  4. Array.findIndex

回傳第一個滿足條件的元素的index  

  Array.findIndex(callback(element[, index[, array]])[, thisArg])

繼續使用上一個範例,而回傳的值變成John Cena的index(index從零開始)  

const employees = [
  { name: 'David Carlson', age: 30 },
  { name: 'John Cena', age: 34 },
  { name: 'Mike Sheridan', age: 25 },
  { name: 'John Carte', age: 50 }];

const index = employees.findIndex(function (employee) {
  return employee.name.indexOf('John') > -1;});

console.log(index); // 1 

  等同:

const employees = [
  { name: 'David Carlson', age: 30 },
  { name: 'John Cena', age: 34 },
  { name: 'Mike Sheridan', age: 25 },
  { name: 'John Carte', age: 50 }];

let index = -1;

for(let i = 0; i < employees.length; i++) {
  if(employees[i].name.indexOf('John') > -1) {
    index = i;
    break;
  }}

console.log(index); // 1 
  • 使用findIndex的好處:
    • 使用簡短的程式就能快速找到任何元素的index
    • 一找到符合條件的即停止,無須額外的break
    • 其實都和find差不多,但使用findIndex可更簡易和避免建立額外的變數去儲存index

下回再繼續整理接下來的兩個~  

心靈成長-"灰階思考"摘要分享 #前篇
let’s encrypt ssl憑證程式certbot不支援ubuntu 14 04

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
Guest
2025/06/09, 週一

Captcha 圖像