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

JavaScript代码报错:无法读取null的indexOf属性,求解决方案

报错原因分析
  • 当String.prototype.match()方法没有匹配到任何结果时,会返回null而非空数组。调用letsMatch('totititiTo', 'r')时,目标字符串里不存在字符'r',所以result变量的值是null,此时调用null.indexOf()就会抛出「无法读取null的属性」的类型错误。
  • 代码还存在其他隐性问题:
    • 未定义变量fiveT:逻辑里用到的fiveT没有声明,后续执行到相关代码会直接报错。
    • 错误的判断条件:indexOf()找不到目标元素时返回的是-1,不是null,所以findNegIndex === null的判断永远不会成立。
代码修复方案

针对上述问题,修复后的代码如下:

const letsMatch = (string, char) => {
  const newRegex = new RegExp(char, "gi");
  let result = string.match(newRegex);
  
  // 先判断是否匹配到结果,没匹配到直接返回0
  if (!result) {
    return 0;
  }

  // 匹配到2个结果时计算位置差
  if (result.length === 2) {
    const findFirstIndex = string.indexOf(char);
    const findSecondIndex = string.indexOf(char, findFirstIndex + 1);
    return findSecondIndex - findFirstIndex + 2;
  } else {
    return 0;
  }
}

console.log(letsMatch('totititiTo', 'r')); // 输出0
console.log(letsMatch('totititiTo', 't')); // 输出对应计算值

修复说明:

  • 增加!result的判断,直接处理无匹配的情况,避免调用null的方法。
  • 将未定义的fiveT替换为函数参数string,确保逻辑在原字符串中查找位置。
  • 移除了无用的findNegIndex判断,因为无匹配的情况已经被提前处理。
  • 简化了返回逻辑,去掉不必要的变量赋值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:24:25