在检查子字符串是否存在时,我一直在这样做:
var that = "ok hello cool";
if( that.indexOf('hello') + 1 ) {
}而不是:
if( that.indexOf('hello') != -1 ) {
}我是忽略了什么,还是有理由不这么做。
是的,我确实不知道有一种更简单的方法:
if ( ~that.indexOf( 'hello' ) ) {
}您可以在这里阅读~位运算符和其他奇异位运算符:https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_运算符。
发布于 2012-07-23 19:03:12
以下是最常见的方法:
if ( ~that.indexOf( 'hello' ) ) {
}~运算符做了一些魔术,只转换-1为0,因此它是唯一的假值。
发布于 2012-07-23 18:59:45
好吧,我相信第二个更明显的是发生了什么.
if( that.indexOf('hello') != -1 ) {
}不过,这两个表达式都是有效的,而且完全没有问题。
https://codereview.stackexchange.com/questions/13941
复制相似问题