I wrote an if condition where the return value is the indexOf
an array. The if condition is failing when the first object of the array is returned (index of which is 0). Is there any way to fix this?
I'm checking if the value term
is present in the array.
My code is:
if (array.indexOf(term)) {
//do something
}
else {
alert("error");
}
-
I'm guessing you're running into a null exception of some sort. This question is in java, but it explains the same concept (just adapt it to javascript)ryanyuyu– ryanyuyu2015年05月07日 20:09:09 +00:00Commented May 7, 2015 at 20:09
-
You are missing a closing parenthesis. Was that a copy/paste error?Jason– Jason2015年05月07日 20:10:29 +00:00Commented May 7, 2015 at 20:10
-
4if(array.indexOf(term)>-1) is the usual way.Sidd– Sidd2015年05月07日 20:10:31 +00:00Commented May 7, 2015 at 20:10
-
@Jason yeah a copy paste error. corrected it.pal– pal2015年05月07日 20:11:12 +00:00Commented May 7, 2015 at 20:11
-
@pal You fixed it wrong. The parenthesis belongs on the first line.Barmar– Barmar2015年05月07日 20:14:34 +00:00Commented May 7, 2015 at 20:14
3 Answers 3
This happens because 0
is falsy in JavaScript. Consider this sample:
if (0) {
console.log("will never run");
}
That log()
call will, as implied, never run.
You can do something like:
if(array.indexOf(term) > -1) {
// do stuff
}
Or a more meaningful comparison, depending on context.
Comments
The indexOf()
function returns the index of the element in the array. If it's not found, it will return a -1. Thus you must check if indexOf()
returns a value greater than -1. If true, it is in the array.
Comments
You can also use the bitwise NOT operator (~
) to quickly check whether the index of something means it contains it or not. For instance...
if(~[].indexOf('no')) { // Evaluates to 0
console.log('Bitwise NOT of -1 evalautes to true'); // It doesn't
} else if (~['test'].indexOf('test')) { // Evaluates to something other than 0
console.log('Bitwise NOT of 0 evalautes to true'); // It does
}