我今天遇到了一些困惑,"string".indexOf('');
总是返回 0
,但我希望 -1
(对于 false
);相反,"string".lastIndexOf('');
总是返回 6
lastIndexOf
更容易理解,因为字符串的长度为 6 个字母("string".length
,从零开始返回 5
)但我在 ECMAscript 规范(5.1 或 6.0)中没有看到任何地方描述为什么 ''
会被视为单词/字符边界
这里到底发生了什么?
最佳答案
规范说:
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
.
关于javascript - 为什么 ''(空字符串)会渗透所有字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33132913/