jQuery .inArray()总是如此?

Cha*_*rsh 16 arrays jquery

我正在尝试使用inarray,但它总是回归真实?有任何想法吗?(所有李正在展示)

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

// get the select
var $dd = $('#product-variants-option-0');

if ($dd.length > 0) { // make sure we found the select we were looking for

    // save the selected value
    var selectedVal = $dd.val();

    // get the options and loop through them
    var $options = $('option', $dd);
    var arrVals = [];
    $options.each(function(){
        // push each option value and text into an array
        arrVals.push({
            val: $(this).val(),
            text: $(this).text()
        });
    });




};

//This is where it is returning true...


if($.inArray('Aqua', arrVals)) {
    $("#select-by-color-list li#aqua").show();
    };
    if($.inArray('Army', arrVals)) {
    $("#select-by-color-list li#army").show();
    };
Run Code Online (Sandbox Code Playgroud)

use*_*716 53

你需要这样做:

if( $.inArray('Aqua', arrVals) > -1 ) {
Run Code Online (Sandbox Code Playgroud)

或这个:

if( $.inArray('Aqua', arrVals) !== -1 ) {
Run Code Online (Sandbox Code Playgroud)

$.inArray()方法返回项的0基础索引.如果没有项目,则返回-1,该if()语句将视为true.

来自文档:

因为JavaScript将0视为松散等于false(即0 == false,但是0!== false),如果我们检查数组中是否存在值,我们需要检查它是否不等于(或大于)-1.


编辑:不是将两个值作为对象推送到数组中,而是使用其中一个,因此您有一个字符串数组,您可以从中构建多个选择器.

一种方法是这样的:

  // 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();
Run Code Online (Sandbox Code Playgroud)

如果数组看起来像:

['Army','Aqua','Bread'];
Run Code Online (Sandbox Code Playgroud)

生成的选择器将如下所示:

$( "#Army,#Aqua,#Bread" ).show();
Run Code Online (Sandbox Code Playgroud)