const result = array.find(callback(element[, index[, array]])[, thisArg]); 其中callback 是一个函数,接收三个参数: element:当前遍历的元素。 index(可选):当前元素的索引。 array(可选):调用 find 方法的数组。 thisArg 可选,用作 callback 的 this 值。
JavaScript Array 对象 实例 获取数组中年龄大于等于 18 的第一个元素索引位置 varages=[3,10,18,20];functioncheckAdult(age){returnage>=18;}functionmyFunction(){document.getElementById("demo").innerHTML=ages.findIndex(checkAdult);} fruits输出结果: ...
var ages = [4, 12, 16, 20]; function checkAdult(age) { return age >= document.getElementById("ageToCheck").value;}function myFunction() { document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);} Try it yourself » JavaScript Array Reference COLOR PICKER LEARN...
ES6为Array增加了find(),findIndex函数。find()函数用来查找目标元素,找到就返回该元素,找不到返回undefined,而findIndex()函数也是查找目标元素,找到就返回元素的位置,找不到就返回-1。 他们的都是一个查找回调函数。 查找函数有三个参数。 value:每一次迭代查找的数组元素。 index:每一次迭代查找的数组元素索引。
findIndex() Return Value Returns theindexof thefirst elementin the array that satisfies the given function. Returns-1if none of the elements satisfy the function. Example 1: Using findIndex() method // function that returns even numberfunctionisEven(element){returnelement %2==0; ...
JavaScript findIndex() 方法 JavaScript Array 对象 实例 获取数组中年龄大于等于 18 的第一个元素索引位置 varages=[3,10,18,20];functioncheckAdult(age){returnage>=18;}functionmyFunction(){document.getElementById("demo").innerHTML=ages.findIndex(checkAdult);}...
console.log(users.find(user => user.age === 22)); //console //{ id: 1, name: 'John', age:22} 例b: 寻找数组中第一个素数 function isPrime(element, index, array) { let start = 2; while (start <= Math.sqrt(element)) { ...
array.find()是一个数组方法,用于在数组中查找满足指定条件的第一个元素,并返回该元素。如果找到匹配的元素,则返回该元素;否则返回undefined。 array.find()方法接受一个回调函数作为参数,该回调函数可以接受三个参数:当前元素、当前索引和原始数组。回调函数应返回一个布尔值,用于判断当前元素是否满足条件。
array.filter(function(value,index,arr){},thisArg) filter方法会为每一个array数组的的值调用回调函数 返回一个包含回调函数为其返回true的所用值得新数组thisArg可选 如果不传为undefined 传值的时候可在回调函数中通过this关键字调用 var num = [1,2,5,8,10]; ...
Array.prototype.every() Array.prototype.some() Array.prototype.filter() 用于过滤数组的某些元素然后返回剩下的元素 传入的函数依次作用于每个元素,然后根据返回值是true或者false来决定是否保留该元素,返回true则留下该元素 回调函数接收三个参数 function(element, index, self) ...