当验证字符不在字符串中时,使用 if(string.indexOf("x") < 0) { ... }
时两者是否相同?或 if(string.indexOf("x") == -1) { ... }
?
在某些情况下 string.indexOf("x")
将是 -2
还是更低?
感谢您分享您的经验。
最佳答案
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
.
关于JavaScript - 使用 indexOf() 在字符串中搜索字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36549619/