zoukankan      html  css  js  c++  java
  • 数组实现一个findLastIndex的方法

    Js 数组为我们提供了很多的数据查找与遍历的方法

    例如:find,findIndex,
    但是没有一个倒序查找的方法,我们可以模拟实现一个 findLastfindLastIndex的方法

    const findLast = function(array, cb){
      if(!Array.isArray(array)){
        return undefined
      }
      if(array.length === 0){
        return undefined
      }
      for(var i = array.length - 1; i >= 0; i--){
        const item = array[i];
        if (cb.call(null, item, i, array)) {
          return item
        }
      }
      return undefined
    }
    

    测试一下

    findLast([1,2,3], (item) => item > 1)
    
    const findLastIndex = function(array, cb){
      if(!Array.isArray(array)){
        return -1
      }
      if(array.length === 0){
        return -1
      }
      for(var i = array.length - 1; i >= 0; i--){
        const item = array[i];
        if (cb.call(null, item, i, array)) {
          return i
        }
      }
      return -1
    }
    

    测试一下

    findLastIndex([1,2,3], (item) => item > 1)
    
  • 相关阅读:
    ubuntu命令
    mac获取root权限
    centos7安装解压缩工具 ncompress
    ubuntu17.04 配置go环境变量
    vue.js 拦截器
    ubuntu 安装jdk
    ubuntu安装deb文件
    初识 阿里云 SSL 证书申请
    java之XML
    LanProxy 内网映射穿透
  • 原文地址:https://www.cnblogs.com/recode-hyh/p/14923070.html
Copyright © 2011-2022 走看看