为什么''(空字符串)会渗透所有字符串?

Why does '' (empty string) permeate all strings?

我今天 运行 有点困惑,"string".indexOf(''); 总是 returns 0,但我希望 -1(对于 false);相反,"string".lastIndexOf(''); 总是 returns 6

lastIndexOf 更容易理解,因为字符串长度为 6 个字母("string".length,索引为零 returns 5)但我看不到任何地方在 ECMAscript 规范 (5.1 or 6.0) 中描述了 为什么 '' 会被视为 word/character 边界

这里到底发生了什么?

规范说:

Return the smallest possible integer k not smaller than start such that k+searchLen is not greater than len, and for all nonnegative integers j less than searchLen, the character at position k+j of S is the same as the character at position j of searchStr; but if there is no such integer k, then return the value -1.

由于vacuous truth,该条件在位置 0 处得到满足:因为您正在搜索空字符串,所以您能想到的任何语句都适用于每个字符,因为它没有字符。

更正式地说,对于任何陈述 P,如果 S = ∅P(x) 成立 ∀ x ∈ S