find(),findIndex(),includes()的使用
程序员文章站
2023-12-23 12:33:16
...
find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
<script>
//find()方法
let arr = [2, 3, 4, 5, 34, 45, 56, 78, 56, 78, 89, 80];
let newArray3 = arr.find(item => item > 5);
console.log(newArray3);//输入的是满足大于5的第一个数所以是34
//不满足的情况下输出undefined
let arr1 = [2, 3, 4, 5];
let newArray4 = arr1.find(item => item > 5);
console.log(newArray4);//不满足条件输入undefined
</script>
findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1
<script>
//findIndex()方法
//满足返回大于10的索引值34从零开始也就是4
let arr = [2,3,4,5,34,45,56,78,56,78,89,80];
let newArray4 = (item => item>10);
console.log(arr.findIndex(newArray4));
//不满足返回-1
let arr1 = [2,3,4,5,];
let newArray5 = (item => item>10);
console.log(arr1.findIndex(newArray5));
</script>
includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false
<script>
//includes()
let arr = [2,3,4,5,34,45,56,78,56,78,89,80];
//包含2返回ture
console.log(arr.includes(2));
//不包含返回false
console.log(arr.includes(1));
</script>