1. array.indexOf
推断数组中是不是存在某个值,假如存在返回数组元素的下标,不然返回-1
let arr = ['something', 'anything', 'nothing', 'anything']; let index = arr.indexOf('nothing'); # 效果:2
2. array.includes(searchElement[, fromIndex])
推断一个数组是不是包括一个指定的值,假如存在返回 true,不然返回false。
参数:searchElement
须要查找的元素值。
参数:thisArg(可选)
从该索引处最先查找 searchElement。假如为负值,则按升序从 array.length + fromIndex 的索引最先搜刮。默以为 0。
let numbers = [12, 5, 8, 130, 44]; let result = numbers.includes(8); # 效果: true result = numbers.includes(118); # 效果: false
3. array.find(callback[, thisArg])
返回数组中满足前提的第一个元素的值,假如没有,返回undefined
参数:callback
element 当前遍历到的元素。
index 当前遍历到的索引。
array 数组自身。
参数:thisArg(可选)
指定 callback 的 this 参数。
// ---------- 元素是一般字面值 ---------- let numbers = [12, 5, 8, 130, 44]; let result = numbers.find(item => { return item > 8; }); # 效果: 12 // ---------- 元素是对象 ---------- let items = [ {id: 1, name: 'something'}, {id: 2, name: 'anything'}, {id: 3, name: 'nothing'}, {id: 4, name: 'anything'} ]; let item = items.find(item => { return item.id == 3; }); # 效果: Object { id: 3, name: "nothing" }
4. array.findIndex(callback[, thisArg])
返回数组中满足前提的第一个元素的索引(下标), 假如没有找到,返回-1
参数:callback
element 当前遍历到的元素。
index 当前遍历到的索引。
array 数组自身。
参数:thisArg(可选)
指定 callback 的 this 参数。
// ---------- 元素是一般字面值 ---------- let numbers = [12, 5, 8, 130, 44]; let result = numbers.findIndex(item => { return item > 8; }); # 效果: 0 // ---------- 元素是对象 ---------- let items = [ {id: 1, name: 'something'}, {id: 2, name: 'anything'}, {id: 3, name: 'nothing'}, {id: 4, name: 'anything'} ]; let index = items.findIndex(item => { return item.id == 3; }); # 效果: 2