//! find 和 findIndex // find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。 const array1 = [5, 12, 8, 130, 44]; const found = array1.find((element) => element > 10); console.log(found); // array1.find( // (e) => { // console.log(`output->this`, this); // return e > 12; // }, // { a: '1' } // ); //! 手写find方法 function find(target, callbackFn, thisArg) { // 判断target 是不是数组 if (!Array.isArray(target)) { return undefined; } for (let i = 0, l = target.length; i < l; i++) { let cur = target[i]; // 当前遍历的元素 let ret = callbackFn.call(thisArg, cur, i, target); if (ret) { return cur; } } } // console.log( // find(array1, (e) => { // console.log(`output->this`, this); // return e > 10; // }) // ); // console.log( // find( // array1, // function (e) { // console.log(`output->this`, this); // return e > 10; // }, // { a: 'a' } // ) // ); //! findIndex // findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。 console.log(array1.findIndex((e) => e > 10)); // 1 console.log(array1.findIndex((e) => e > 1000)); // 如果没有满足的 就返回 -1