Why doesn’t inArray detect capital letters?

Asked

Viewed 54 times

3

I don’t understand why when I look for PALAVRA the inArray() jQuery does not find it. But if I look for palavra is positive when the array is PALAVRA.

The first test I expected to be positive does not work, why? In the manual it says that the comparison of values is strict, which means 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

  • PS: The in_array of PHP is case sensitive and works as expected. Will it be a pro Nannannannannan, Batman?

  • As a joke, I could switch to Mootools :) and use the contains(), where the name is more according to what the code does :)

  • 1

    The ~ in its solution is master stroke, it was worth asking without having read the manual carefully :) In fact, it is a plugin pro Stackedit.io, has to be jQ, but it was worth the tip!

1 answer

6


The problem is that the inArray does not give a boolean as the name suggests. It gives the element’s input in the array.

In your first case it gives 0, hence the if fail.

In the second case where the if gives true, using "{extensions}" with small letter, this element does not exist in the array, hence the -1, and the if resolve 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;
},

Apparently the vMore modern ersão has this code (below) but which is essentially identical:

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

So in your code you can replace the ifs for:

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

Example: http://jsfiddle.net/1ubr2gsn/3/

  • 1

    Oh, Dear, of course, you have to $.inArray( title1, titles ) > 0 then. Merci!

  • 1

    @brasofilo or if(~$.inArray( title1, titles )){ - http://jsfiddle.net/1ubr2gsn/3/

  • 2

    Olé!

  • 4

    $.inArray( title1, titles ) > 0 is wrong too, since 0 is a valid index, so the correct would be $.inArray( title1, titles ) > -1, since when he does not find the return will always be -1

  • Óxênte, did you not accept this? Unacceptable!

  • @brasofilo :) np, I noticed only now also.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.