JavaScript中lastIndexOf("")返回10为何不是-1?
JavaScript lastIndexOf("") 返回10的原因解析
先看你提供的测试代码:
let study = "javascript"; console.log(study.length); // 10 // search chr only console.log(study.lastIndexOf('t')); // 9; 't' is found at index 9 console.log(study.lastIndexOf('v')); // 2; 'v' is found at index 2 console.log(study.lastIndexOf()); // -1; [empty] is not found console.log(study.lastIndexOf("")); // 10; [nothing] is found at index 10, strange result console.log(study.lastIndexOf(" ")); // -1; space is not found
核心原因:空字符串的匹配规则
lastIndexOf("")返回10是完全符合JavaScript规范的:
- 空字符串
""被定义为可以匹配在字符串的所有字符间隙,包括字符串开头(索引0之前)和结尾(等于字符串长度的位置,也就是最后一个字符索引+1的位置)。 - 对于长度为10的
"javascript",最后一个字符的索引是9,字符串结束的位置就是索引10,这是空字符串能匹配到的最靠后的位置,所以lastIndexOf返回10。
补充:无参数 vs 传空字符串的区别
- 直接调用
lastIndexOf()时,相当于传入了undefined,目标字符串中不存在这个值,所以返回-1; - 传入
""是明确搜索空字符串,会按照上述规则匹配到末尾位置。
内容的提问来源于stack exchange,提问作者Paco67
相关产品推荐
相关产品推荐

