代码之家  ›  专栏  ›  技术社区  ›  feihcsim

如何找到从数组末尾开始的数组元素?

  •  1
  • feihcsim  · 技术社区  · 6 年前

    JavaScript有如下数组方法 indexOf find 索引 会是 lastIndexOf 找到 它从数组的末尾开始,就像 Ramda's findLast

    我宁愿两者都不用 array.slice().reverse().find() 由于性能成本或 for

    3 回复  |  直到 6 年前
        1
  •  2
  •   ggorlen Hoàng Huy Khánh    6 年前

    你可以用 reduceRight but possible )找到匹配的东西就早点回来 for 回路:

    const lastIndexOf = (needle, haystack) => 
      haystack.reduceRight((a, e, i) => 
        a >= 0 ? a : e === needle ? i : -1
      , -1)
    ;
    
    const arr = [1,4,3,5,5,4,5];
    console.log(lastIndexOf(4, arr));
    console.log(lastIndexOf(2, arr));

    还有递归,它也有类似的效率问题(堆栈帧开销,没有即时的提前返回,必须写一个助手或额外的条件,如果数组很大,你会毁掉堆栈…):

    const lastIndexOf = (needle, haystack, idx) => 
      lastIndexOfHelper(needle, haystack, haystack.length - 1)
    ;
    
    const lastIndexOfHelper = (needle, haystack, idx) => 
      idx < 0 || haystack[idx] === needle ? 
        idx : lastIndexOfHelper(needle, haystack, idx - 1)  
    ;
    
    const arr = [1,4,3,5,5,4,5];
    console.log(lastIndexOf(4, arr));
    console.log(lastIndexOf(2, arr));
        2
  •  2
  •   Jonas Wilms    6 年前

    不,没有,但是你可以很容易地填好它:

     Array.prototype.findLast = function(fn) {
      for(let i = this.length - 1; i >= 0; i--) 
        if(fn( this[i], i, this )) return this[i];
      return null;
     };
    
    
    
    console.log([5,4,3,2,1].findLast(el => el > 3));
    
        3
  •  1
  •   user3666653    6 年前