1.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //! find 和 findIndex
  2. // find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
  3. const array1 = [5, 12, 8, 130, 44];
  4. const found = array1.find((element) => element > 10);
  5. console.log(found);
  6. // array1.find(
  7. // (e) => {
  8. // console.log(`output->this`, this);
  9. // return e > 12;
  10. // },
  11. // { a: '1' }
  12. // );
  13. //! 手写find方法
  14. function find(target, callbackFn, thisArg) {
  15. // 判断target 是不是数组
  16. if (!Array.isArray(target)) {
  17. return undefined;
  18. }
  19. for (let i = 0, l = target.length; i < l; i++) {
  20. let cur = target[i]; // 当前遍历的元素
  21. let ret = callbackFn.call(thisArg, cur, i, target);
  22. if (ret) {
  23. return cur;
  24. }
  25. }
  26. }
  27. // console.log(
  28. // find(array1, (e) => {
  29. // console.log(`output->this`, this);
  30. // return e > 10;
  31. // })
  32. // );
  33. // console.log(
  34. // find(
  35. // array1,
  36. // function (e) {
  37. // console.log(`output->this`, this);
  38. // return e > 10;
  39. // },
  40. // { a: 'a' }
  41. // )
  42. // );
  43. //! findIndex
  44. // findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。
  45. console.log(array1.findIndex((e) => e > 10)); // 1
  46. console.log(array1.findIndex((e) => e > 1000)); // 如果没有满足的 就返回 -1