js 数组的find和findIndex

Array.find()

array.find(function(currentValue, index, arr),thisValue)
参数描述
function(currentValue, index,arr)必需。数组每个元素需要执行的函数。
函数参数:
参数描述
currentValue必需。当前元素
index可选。当前元素的索引值
arr可选。当前元素所属的数组对象
thisValue 可选。 传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值
var ages = [3, 10, 18, 20];
 
function checkAdult(age) {
    return age >= 18;
}
 
function myFunction() {
    document.getElementById("demo").innerHTML = ages.find(checkAdult);
}
let array1 = [5, 12, 8, 110, 88];
 
let found = array1.find(element => {
  return element > 10;
});
 
console.log(found);
// output: 12

Array.findIndex()

array.findIndex(function(currentValue, index, arr), thisValue)
参数描述
function(currentValue, index,arr)必须。数组每个元素需要执行的函数。
函数参数:
参数描述
currentValue必需。当前元素
index可选。当前元素的索引
arr可选。当前元素所属的数组对象
thisValue 可选。 传递给函数的值一般用 "this" 值。
如果这个参数为空, "undefined" 会传递给 "this" 值
var ages = [4, 12, 16, 20];
 
function checkAdult(age) {
    return age >= document.getElementById("ageToCheck").value;
}
 
function myFunction() {
    document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);
}
var allPeple = [{
	name: '小王',
	id: 14
},{
	name: '大王',
	id: 41
},{
	name: '老王',
	id: 61
}]
				
var myTeamArr = [{
	name: '小王',
	id: 14
}]
				
var PId = 14; //假如这个是要人的ID
 
function testFunc(item){return item.id == PId ;}
 
//判断myteam里是不是有这个人,如果==-1 代表没有,在allPeople中找到他,添加入我的队伍
 
myTeamArr.findIndex(testFunc) == -1 
    ? myTeamArr.push(allPeple.find(testFunc)) 
    : alert('已存在该人员');

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值