Array 擴充套件方法
阿新 • • 發佈:2021-08-10
1. find()方法
find()方法查詢陣列中符合條件的第一個元素,並將其返回;若未查詢到,則返回undefined.
let arr = [{ id: 1, name: "James" }, { id: 2, name: "Messy" }, { id: 3, name: "Messy" }]; console.log(arr.find(value => value.name === "Messy")); // {id: 2, name: "Messy"} console.log(arr.find(value => value.name === "John")); //undefined
聯想到 some() 【還有every()】方法: 查詢陣列中所有元素,若有任何一個符合條件,則返回true;否則返回false.
console.log(arr.some(value => value.name === "Messy")); // true
2. findIndex() 方法,在一個數組中查詢某個元素的位置,若存在此元素,則返回其索引;否則返回-1.
let arr = [10, 20, 20, 30]; let idx = arr.findIndex((value, index) => { return value === 20; }) console.log(idx);// 1
3. includes() 方法,類似於字串中的 includes() 方法,尋找一個數組中是否存在該元素,存在返回true;否則返回false.
let arr = [10, 20, 20, 30]; console.log(arr.includes(10)); // true