Reputation: 3174
I was wondering why / when -1
is used in JavaScript or jQuery, respectively.
I'm using this snippet:
if ($.inArray('false', answers) > -1) {
window.console.log('you Lose!');
}
Cheers,
Chris
Upvotes: 1
Views: 81
Reputation: 47099
Because indexes is starting with 0. (0-index).
var arr = ['a', 'b', 'c'];
alert( arr[0] ) // a;
So when checking the index of an element in an array ($.inArray
and [].indexOf
) it would be wrong to return 0 if the element isn't present:
var arr = ['a', 'b', 'c'];
alert( arr.indexOf('a') ); // 0
alert( arr.indexOf('b') ); // 1
alert( arr.indexOf('c') ); // 1
alert( arr.indexOf('d') ); // -1
I would say that jQuery have a design flaw here, I would rather think that jQuery.inArray
would return a boolean (true/false
).
Upvotes: 2
Reputation: 150624
In this case, -1
is returned if the expression you are looking for is not in the array you are looking in.
While, according to its documentation, $.inArray
returns the index of the element (if it was found), an index of -1
is impossible: This is due to the fact that indices start with 0 as lowest possible value.
Hence -1
does just mean a non-valid index position, i.e. not found.
So, in your snippet, the test for > -1
means: Check whether any valid index was found, or in other words, check whether the given value was in the array.
This is even mentioned in the documentation:
Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.
Hope this helps :-)
Upvotes: 3