如何检查字符串是否为.inarray

如何检查我的数组中是否包含字符串? 以下是我将arrays放在一起的方法……

// get the select var $dd = $('#product-variants'); 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() }); }); }; 

我想检查数据中是否包含“Kelly Green”,如果它是我想要的话

 $("#select-by-color-list li#kelly-green").show(); 

你可以使用jQuery的内置.inArray()方法:

 if($.inArray('Kelly Green', arrVals) != -1) { $("#select-by-color-list li#kelly-green").show(); } 

其他答案是正确的,因为在这里使用$.inArray()但是使用是关闭的,它应该是:

 if($.inArray('Kelly Green', arrVals) != -1) { $("#select-by-color-list li#kelly-green").show(); } 

$.inArray()返回数组中的位置 (如果它是第一个则可能为0 ……所以它在那里,但if()将为false)。 要检查它是否存在,请使用!= -1 ,如果找不到该元素,它将返回。

试试这个:

 console.log($.inArray('Kelly Green', arrVals); if($.inArray('Kelly Green', arrVals) { $("#select-by-color-list li#kelly-green").show(); } 

可能的欺骗: 需要关于jQuery $ .inArray()的帮助