Menu
CoddyTech

Find 和 FindIndex 方法

本课属于 Coddy JavaScript 学习旅程的“逻辑与流程”单元。第 58 课,共 65 课。

find() 方法会返回数组中第一个满足给定测试函数的元素。如果找不到元素,则返回 undefined。

findIndex() 方法与它类似,但返回第一个匹配元素的索引,而不是元素本身。如果没有找到元素,它会返回 -1。

基本语法:

array.find(callback(element[, index[, array]]))
array.findIndex(callback(element[, index[, array]]))

使用 find() 的简单示例:

const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(num => num > 10);
console.log(found);
// 12(第一个大于 10 的数字)

使用 findIndex() 的相同示例:

const numbers = [5, 12, 8, 130, 44];
const foundIndex = numbers.findIndex(num => num > 10);
console.log(foundIndex);
// 1(第一个大于 10 的数字的索引)

在数组中查找对象:

const inventory = [
	{name: 'apples', quantity: 2},
	{name: 'bananas', quantity: 0},
	{name: 'oranges', quantity: 5}
];

// 使用 find
const result = inventory.find(item => item.name === 'bananas');
console.log(result); // {name: 'bananas', quantity: 0}

// 使用 findIndex
const index = inventory.findIndex(item => item.name === 'bananas');
console.log(index); // 1

亲手试试

这节课没有代码挑战。

quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: JavaScript 在线编译器