作用:
find() 办法返回通过测试(函数内判断)的数组的第一个元素的值。
find() 办法为数组中的每个元素都调用一次函数执行:
- 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
- 如果没有符合条件的元素返回 undefined
语法:
array.find(function(currentValue, index, arr),thisValue)
- currentValue,必须。以后元素
- index,可选。以后元素的索引值
- arr,可选。以后元素所属的数组对象
- thisValue,可选。 传递给函数的值个别用 "this" 值。如果这个参数为空,"undefined" 会传递给 "this" 值
留神:
find() 对于空数组,函数是不会执行的。
find() 并没有扭转数组的原始值。
实例:
const array1 = [5, 12, 8, 130, 44];const found = array1.find(element => element > 10);console.log(found);//12//用对象的属性查找数组里的对象var inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5}];function findCherries(fruit) { return fruit.name === 'cherries';}console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }