JS中find方法的使用
JS中find方法的使用
文章共372字 · 阅读需要大约2分钟
一键AI生成摘要,助你高效阅读
问答
·
一:概念
find()方法用于查找数组中符合条件的第一个元素,如果没有符合条件的元素,则返回undefined
注意:
find() 对于空数组,函数是不会执行的。
find() 并没有改变数组的原始值。
二:语法
array.find(function(currentValue, index, arr),thisValue)
参数
callback:必须。为数组中每个元素执行的函数,该函数接受三个参数:
currentValue:必须。数组中正在处理的当前元素。
index:可选。当前元素的索引值。
arr:可选。当前元素所在的数组对象。
thisValue:可选。传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值
三:实例
1、求数组中第一个大于1的值
let arr1 = [1, 2, 3, 4, 5];
let num = arr1.find(item => item > 1);
console.log(num) //輸出的結果是2
2、提取第一个id为1的对象
var arr = [{
id: 1,
name: '张一',
age: 25,
class: '一班'
}, {
id: 1,
name: '张二',
age: 25,
class: '二班'
}, {
id: 2,
name: '张三',
age: 25,
class: '三班'
}]
let obj = arr.find(item => item.id == 1)
console.log(obj);
// 结果:{id: 1, name: '张一', age: 25, class: '一班'}
更多推荐
已为社区贡献1条内容
所有评论(0)