find()
方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
;找到满足条件,后续代码不执行。
用法
-
find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。
-
如果没有符合条件的元素返回 undefined
-
find() 对于空数组,函数是不会执行的。
-
find() 并没有改变数组的原始值。
-
array.find(function(currentValue, index, arr),thisValue),其中currentValue为当前项,index为当前索引,arr为当前数组
例子:
let test = [1, 2, 3, 4, 5];
let a = test.find(item => item > 3);
console.log(a); //4
let b = test.find(item => item == 0);
console.log(b); //undefined
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(item) {
return item.name === 'bananas';
}
console.log(inventory.find(findCherries)); // { name: 'bananas', quantity: 0 }
判断对象里的值是否为空,以此来满足一些要求
// 必填参数的判断
const checkGoOrderInfoForm: keysType = {
goDate: '去程日期',
goDepartureTime: '去程发车时间段',
goBeginStopId: '去程上车站点',
goEndStopId: '去程下车站点',
goRunId: '去程班次'
};
const errorKey1 = Object.keys(checkGoOrderInfoForm).find((key) => !param[key]);
if (errorKey1) {
Taro.showToast({
title: checkGoOrderInfoForm[errorKey1],
icon: 'none',
duration: 3000
});
return;
}