jQuery .inArray() always true?

后端 未结 2 1412
情话喂你
情话喂你 2020-12-01 16:03

I\'m trying to use inarray but its always returning true? Any ideas? (all li\'s are showing)

$(\"#select-by-color-list li\").hide();

// get the select
var $         


        
相关标签:
2条回答
  • 2020-12-01 16:50

    ES6 to the rescue! Although not jQuery I thought worth answering for future readers...

    ES6 introduces .includes() which works as you think $.inArray SHOULD work:

    const myArray = ["a", "b", "c"];
    
    console.log(myArray.includes("a")) /* true */
    console.log(myArray.includes("d")) /* false */

    Array.prototype.includes()

    0 讨论(0)
  • 2020-12-01 17:00

    You need to do this:

    if( $.inArray('Aqua', arrVals) > -1 ) {
    

    or this:

    if( $.inArray('Aqua', arrVals) !== -1 ) {
    

    The $.inArray() method returns the 0 based index of the item. If there's no item, it returns -1, which the if() statement will consider as true.

    From the docs:

    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.


    EDIT: Instead of pushing both values into the array as an object, just use one or the other, so you have an Array of strings from which you can build a multiple selector.

    One way is like this:

      // Create an Array from the "value" or "text" of the select options
    var arrVals = $.map( $dd[0].options, function( opt, i ){
        return opt.value || opt.text;
    });
    
      // Build a multiple selector by doing a join() on the Array.
    $( "#" + arrVals.join(',#') ).show();
    

    If the Array looks like:

    ['Army','Aqua','Bread'];
    

    The resulting selector will look like:

    $( "#Army,#Aqua,#Bread" ).show();
    
    0 讨论(0)
提交回复
热议问题