Why inArray does not detect uppercase?

3

I do not understand why when I search for PALAVRA inArray() jQuery does not find it. But if I look for palavra gives positive, when in array it is PALAVRA .

The first test I expected positive does not work, why? In the manual says that the comparison of values is strict, what does it mean in this case?

var titles = ['{EXTENSIONS}', '{dummy}'];

var title1 = "{EXTENSIONS}";
if( $.inArray( title1, titles ) ) {
    $('#txt1').text('No!'); // Não entra
}

var title2 = "{extensions}";
if( $.inArray( title2, titles ) ) {
    $('#txt2').text('Yes!'); // Entra
}

var title3 = "{dummy}";
if( $.inArray( title3, titles ) ) {
    $('#txt3').text('Yes!');
}

JSFiddle

    
asked by anonymous 22.09.2014 / 20:48

1 answer

6

The problem is that inArray does not give a boolean as the name implies. It gives the index of the element in the array.

In its first case it gives 0 , hence if fails.

In the second case where if gives true, using "{extensions}" with small print, this element does not exist in the array, hence the index is -1 , and if solve true . >

If we take a look at the source code:

inArray: function( elem, array ) {
    if ( array.indexOf ) {
        return array.indexOf( elem );
    }
    for ( var i = 0, length = array.length; i < length; i++ ) {
        if ( array[ i ] === elem ) {
            return i;
        }
    }
    return -1;
},

As seen av more modern version has this code (in low) but that in the background is identical:

inArray: function( elem, arr, i ) {
    return arr == null ? -1 : indexOf.call( arr, elem, i );
},

So in your code you can replace the% s of% s with:

if( ~$.inArray(valor, array) ){
// ou
if($.inArray(valor, array) > -1){

Example: link

    
22.09.2014 / 20:58