What's the preferred operator when comparing indexOf result with -1, "!=" or ">"?
What's the preferred ope开发者_StackOverflow中文版rator when comparing the result of indexOf with -1, "!=" or ">"? Is there any difference?
Either is ok here, you just care that it's not -1
. Personally, I prefer !=
, since I'm saying it's explicitly not something that way...and that's the check we're performing. For example:
if(arr.indexOf("thing") != -1)
It's checking explicitly for not that single value, the unique -1
result you get when it's not found. With >
, you're checking for any other value...I find this more explicit, just use what's clearer for you.
Another reason I steer clear of >
is that far too many times (in both questions and answers) on StackOverflow I see if(arr.indexOf("thing") > 0)
which is almost never the correct check.
As Nick said, either is fine. I prefer >= 0
because then I'm coding a positive:
index = str.indexOf('foo');
if (index >= 0) {
// Do something with `index`
}
else {
// 'foo' wasn't found
}
I would say !=
. You said it yourself actually:
when comparing the result of indexOf with -1
Moreover, !=
is faster than >
.
精彩评论