1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- //! 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
|