1、arr.find()
arr.find()是 JavaScript 数组的一个方法,用于查找数组中第一个符合条件的元素。
const arr = [2, 4, 6, 8];
const found = arr.find(element => element > 5);
console.log(found); // 6
除了简单的比较之外,我们还可以利用 find()方法构建更复杂的查找条件。例如:
const people = [
{ name: '张三', age: 25, gender: 'male' },
{ name: '李四', age: 30, gender: 'male' },
{ name: '王五', age: 28, gender: 'female' }];
const found = people.find(person => person.gender === 'female' && person.age > 25);
console.log(found); // {name: "王五", age: 28, gender: "female"}
2、arr.filter()
arr.filter()是找到所有符合条件的记录并以新数组形式展示。
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // [2, 4]
更复杂一点的例如:
const people = [
{ name: '张三', age: 25, gender: 'male' },
{ name: '李四', age: 30, gender: 'male' },
{ name: '王五', age: 28, gender: 'female' }
];
const found = people.filter(person => person.gender === 'female' && person.age > 25);
console.log(found);
//[{name: "王五", age: 28, gender: "female"},{ name: '王五', age: 28, gender: 'female' }]