JavaScript - 使用 indexOf() 在字符串中搜索字符

JavaScript - Searching for a char in string using indexOf()

验证字符不在字符串中时,使用 if(string.indexOf("x") < 0) { ... }if(string.indexOf("x") == -1) { ... } 时是否相同?

在某些情况下 string.indexOf("x") 会是 -2 或更低吗?

感谢您分享您的经验。

它们是相同的:

"The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present."

MDN

Could there be some circumstances when string.indexOf("x") would be -2 or lower?

没有。这不可以。仅当没有匹配项时,索引为负 (-1)。

When verifying that character is NOT in string, is it both the same when using if(string.indexOf("x") < 0) { ... } or if(string.indexOf("x") == -1) { ... }

当然是一样的因为-1<0.

根据 indexOf() specification,它可以 return 一个值:-1(如果未找到子字符串)并且从 0string.length - 1(表示匹配位置)。


更好的方法是使用 ECMAScript 6 method includes():

var string = 'x-files';

string.includes('x'); // prints true