find
find() 方法返回数组中满足条件的第一个元素的值。否则返回 undefined。
// 一维数组
const array = [5, 12, 8, 130, 44];
const number = array.find(item => item > 10);
console.log(number);
// 12
// 二维数组
const list = [
{code: 'hospital', name: '机构'},
{code: 'doctor', name: '医生'},
{code: 'teacher', name: '教师'}
]
const listObj = list.find(it => {
if (it.code === 'doctor') return it;
});
console.log(listObj);
// {code: 'doctor', name: '医生'}
findIndex
findIndex()方法返回数组中满足条件的第一个元素的索引。若没有找到则返回-1。
const array = [5, 12, 8, 130, 44];
const index = array.findIndex(item => item > 10);
console.log(index);
// 1