es6 find 數組內查詢用法

寫在開頭

1.第二次發佈,但願能發佈上
2.每當碰到新的問題搜索時,老是搜索多個結果才能從複雜的答案中理解清楚
3.直到遇到了思否,答案簡單明瞭,一看就懂
但願本身也能很清晰地表達清楚,讓朋友一看就懂,知道何時該用它
之後會努力學習,寫一寫關於前端框架和es6的

es6 find

arr.find(item,index,arr)=>{return item.id == 2}
//(item裏每一項對比,條件)
//item爲循環的每一項
//index爲角標
//arr爲數組

數據數組

const arr = [
        {id:"1",name:"Jim",age:"20"},
        {id:"2",name:"Lily",age:"18",test:"測試"},
        {id:"3",name:"Mei",age:"45"},
        {id:"2",name:"Jane",age:"13"}
    ]

實例問題

尋找id=2 的數據?前端

解決寫法

1.以前for循環寫法es6

let output=[]
for(let i = 0;i<arr.length;i++ ){
    if (arr[i].id==2) {
                         output.push(arr[i])
                      }          
}
// {id: "2", name: "Lily", age: "18", test: "測試"},{id: "2", name: "Jane", age: "13"}

2 用find寫法數組

let output = arr.find((item,index,arr)=>{
   return item.id == '2'
})
// {id: "2", name: "Lily", age: "18", test: "測試"}

總結

  • 數組內數據查詢
  • 當咱們須要查詢出惟一一條數據時,能夠選擇用find
  • 當查詢不到符合條件的數據時,返回 undefined

注意

  • 當find查詢到第一條與條件相符的數據時,會中止查詢,只會查詢出第一條相符數據
  • 不兼容IE瀏覽器 (不包含IE edge)
相關文章
相關標籤/搜索