I recently came to conclusion that $.inArray is not working. I researched everywhere, saw similar threads to jQuery: why doesn't jQuery.inArray() work?
But still I see it as a jQuery Bug. Because I have a ARRAY which I am using in $.inArray
Here is the console.log
var testArray value is:
["1", "15"]
which is obvisouly an array in JavaScript.
And I am using command
if($.inArray(14, testArray))
alert("14 should not be in array. Isn't it?");
I Also tried following, but stil same problem:
if(jQuery.inArray('14', testArray))
alert("14 should not be in array. Isn't it?");
jQuery's $.inArray
method returns an index of where the value is found, or -1
if it is not found. It just so happens that -1
is truthy (convert it to a boolean by running !!-1
), which will evaluate to true. In order to more reliably use this method, compare its return value rather than merely using it as a condition:
if ( $.inArray(14, ["1", "15"]) > -1 ) {
alert( "Value has been found" );
}
This is stated very clearly in the online documentation .
If you're looking for a simpler convention when using this approach, you can invert the bits of the operand and convert -1
to 0
and 0
to -1
:
if ( ~$.inArray(14, ["1", "15"]) )
$.inArray
returns -1
if item is not found. So jQuery isArray
does work properly. That's why when you run your test code:
if ($.inArray(14, testArray)) {
alert("14 should not be in array. Isn't it?");
}
you see alert. Of course, because -1
is not falsy.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.