// 示例代码:使用 indexOf 方法查找数组中的元素
const array = [1, 2, 3, 4, 5];
// 查找元素 3 在数组中的索引
const index = array.indexOf(3);
if (index !== -1) {
console.log(`元素 3 的索引是: ${index}`);
} else {
console.log('元素 3 不在数组中');
}
// 示例代码:使用 find 方法查找数组中满足条件的第一个元素
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
// 查找 id 为 2 的用户
const user = users.find(u => u.id === 2);
if (user) {
console.log(`找到用户: ${user.name}`);
} else {
console.log('未找到该用户');
}
// 示例代码:使用 filter 方法查找数组中满足条件的所有元素
const numbers = [1, 2, 3, 4, 5, 6];
// 查找所有偶数
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(`偶数有: ${evenNumbers.join(', ')}`);
indexOf 方法:用于查找数组中某个元素的索引。如果找到了该元素,则返回其索引;如果没有找到,则返回 -1。find 方法:用于查找数组中满足给定条件的第一个元素,并返回该元素。如果没有找到符合条件的元素,则返回 undefined。filter 方法:用于查找数组中所有满足给定条件的元素,并返回一个包含这些元素的新数组。上一篇:js 数组取交集
下一篇:js each遍历数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站