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

标签 javascript string if-statement indexof

当验证字符不在字符串中时,使用 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/

相关文章:

javascript - 快速按下并调整窗口大小后显示错误的东西

java - StringReader 从 String.Split 输出中给出错误

string - VBA在最后一个单词之后切割字符串总长度小于80个字符

c - 使用 cstdio 读取键盘输入

python - Pandas 根据另一列中的条件计算一列中的数字

javascript - jQuery 根据选择值结合多行(父函数?)从表中填充文本输入

javascript - 发送到模型的属性无效。验证问题

c++ - 嵌套的 if 语句和 "&&"运算符

excel - Excel-有条件地隐藏错误

javascript - iPad Javascript/jQuery touchstart 问题