以下介紹ES5和ES6+ Array的常見用法,也許能讓你寫出來的JS Code看起來更簡潔易懂
主要有八種:
這篇要來介紹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的好處:
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
下回再繼續整理接下來的兩個~