You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Array.prototype.findLastIndex报错not a function,为何MDN显示该方法存在?

为什么调用Array.prototype.findLastIndex会抛出TypeError?

核心原因是当前运行环境不支持ES2022的findLastIndex方法。这个方法是ES2022(ES13)新增的数组方法,旧版本的浏览器(比如Chrome 90之前、Firefox 88之前)或者旧版本的Node.js(v18.0.0之前,或v16.15.0之前的LTS版本)没有内置这个方法,所以调用时会触发TypeError。

解决方案

  • 升级运行环境
    浏览器直接升级到支持ES2022的新版本;Node.js升级到v16.15.0+(LTS)或v18.0.0+版本,就能直接使用findLastIndex。

  • 手动实现等效逻辑
    不想升级的话,自己写代码实现从后往前查找的功能:

    const list = [1,2,100,50,100,20];
    // 从后往前遍历找目标元素
    let targetIndex = -1;
    for (let i = list.length - 1; i >= 0; i--) {
      if (list[i] === 100) {
        targetIndex = i;
        break;
      }
    }
    console.log(targetIndex); // 输出4
    

    或者用反转数组的方式间接计算:

    const list = [1,2,100,50,100,20];
    const reversedList = [...list].reverse();
    const reversedIndex = reversedList.findIndex(item => item === 100);
    const targetIndex = reversedIndex !== -1 ? list.length - 1 - reversedIndex : -1;
    console.log(targetIndex); // 输出4
    
  • 添加Polyfill
    如果无法升级环境,给Array.prototype补一个findLastIndex的实现:

    if (!Array.prototype.findLastIndex) {
      Array.prototype.findLastIndex = function(predicate) {
        for (let i = this.length - 1; i >= 0; i--) {
          if (predicate(this[i], i, this)) {
            return i;
          }
        }
        return -1;
      };
    }
    
    // 补完后就能正常调用了
    const list = [1,2,100,50,100,20];
    const index = list.findLastIndex(item => item === 100);
    console.log(index); // 输出4
    

内容的提问来源于stack exchange,提问作者Shylock Wu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:00:17