关于js的find的基本用法

Array.prototype.find() 是 JavaScript 的一个数组方法,它被用来在数组中查找一个符合条件的元素。一旦找到第一个符合条件的元素, find() 会立即返回这个元素的值,否则返回 undefined。

以下是 find() 方法的基本语法:

arr.find(callback(element[, index[, array]])[, thisArg])
参数:

callback: 回调函数,在数组每个元素上执行,接受三个参数:

currentValue : 数组中正在处理的当前元素。

index (可选): 数组中正在处理的当前元素的索引。

array (可选): find() 方法被调用的数组。

thisArg (可选): 执行回调时用作 this 的对象。

返回值:

返回数组中第一个满足所提供测试函数的元素的值,否则返回 undefined。

1.使用currentValue 参数:

javascript 复制代码
// 例子1:寻找数组中第一个大于10的元素
let array = [5, 12, 8, 130, 44];
/**
我们传给 find() 函数一个回调函数,该函数会对数组的每个元素进行测试。当找到第一个大于10的数时,find() 就立即返回这个数。
*/
let found = array.find(element => element > 10);

console.log(found,'-----------found'); // 输出: 12


2.使用 currentValue 和 index 参数

javascript 复制代码
/**
例子2:除了检查元素是否大于10,我们还检查其索引是否大于2。因此,find() 返回的是第一个在索引大于2且值大于10的元素。
*/
var array2 = [5, 12, 8, 130, 44];

var found = array2.find(function(element, index) {
  return element > 10 && index > 2;
});

console.log(found); // 130

3.使用 currentValue,index 和 arr 参数

javascript 复制代码
/**
例子3:我们查找最后一个元素(索引等于数组长度减一)且该元素大于10的元素。因为44不满足条件,所以返回 undefined。
*/

var array3 = [5, 12, 8, 130, 44];

var found = array3.find(function(element, index, arr) {
  return element > 10 && index === arr.length - 1;
});

console.log(found); // undefined

4.其他

javascript 复制代码
// 例子4:取出testData中与test对应的对象
const testData = ref([{
  id:1,
  name:'测试1'
},{
  id:2,
  name:'测试2'
},{
  id:3,
  name:'测试3'
},{
  id:4,
  name:'测试4'
},])

const test = ref(testData.value[0].id) // 1
const findTest = testData.value.find((item)=> item.id = test.value)

console.log(testData.value,'-----------testData');
console.log(test.value,'-----------test');//1
console.log(findTest,'-----------findTest'); // { id:1, name:'测试1' }
相关推荐
Wenweno0o10 小时前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
于慨10 小时前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
石小石Orz10 小时前
油猴脚本实现生产环境加载本地qiankun子应用
前端·架构
从前慢丶10 小时前
前端交互规范(Web 端)
前端
@yanyu66610 小时前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
CHU72903510 小时前
便捷约玩,沉浸推理:线上剧本杀APP功能版块设计详解
前端·小程序
chenjingming66610 小时前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
GISer_Jing10 小时前
Page-agent MCP结构
前端·人工智能
王霸天10 小时前
💥别再抄网上的Scale缩放代码了!50行源码教你写一个永不翻车的大屏适配
前端·vue.js·数据可视化
小领航10 小时前
用 Three.js + Vue 3 打造炫酷的 3D 行政地图可视化组件
前端·github