JS jQuery – 检查值是否在数组中

我更像是一个PHP人,而不是JS – 我认为我的问题更多是语法问题..

我有一个小jQuery来“validation”并检查输入值。

它适用于单个单词,但我需要数组。

我正在使用jQuery的inArray()

 var ar = ["value1", "value2", "value3", "value4"]; // ETC... jQuery(document).ready(function() { jQuery("form#searchreport").submit(function() { if (jQuery.inArray(jQuery("input:first"), ar)){ //if (jQuery("input:first").val() == "value11") { // works for single words jQuery("#divResult").html("VALUE FOUND").show(); jQuery("#contentresults").delay(800).show("slow"); return false; } // SINGLE VALUE SPECIAL CASE / Value not allowed if (jQuery("input:first").val() == "word10") { jQuery("#divResult").html("YOU CHEAT !").show(); jQuery("#contentresults").delay(800).show("slow"); return false; } // Value not Valid jQuery("#divResult").text("Not valid!").show().fadeOut(1000); return false; }); }); 

现在 – 这个if (jQuery.inArray(jQuery("input:first"), ar))工作正常..我放的每个值都将被validation为OK。 (甚至是空的)

我只需要validation数组中的值(ar)。

我也试过if (jQuery.inArray(jQuery("input:first"), ar) == 1) // 1,0,-1 tried all

我究竟做错了什么 ?

额外的问题:如何在jQuery数组中不做? (相当于PHP if (!in_array('1', $a)) – 我认为它不起作用,需要使用这样的东西: !!~

您正在将jQuery对象( jQuery('input:first') )与字符串(数组的元素)进行比较。
更改代码以便将输入的值(即字符串)与数组元素进行比较:

 if (jQuery.inArray(jQuery("input:first").val(), ar) != -1) 

如果在数组中找不到元素,则inArray方法返回-1 ,因此作为如何确定元素是否不在数组中的奖励答案,请使用:

 if(jQuery.inArray(el,arr) == -1){ // the element is not in the array }; 

关于你的奖金问题,试试if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)

值的替代解决方案检查

 //Duplicate Title Entry $.each(ar , function (i, val) { if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck); }); 

Array.prototype属性表示Array构造函数的原型,并允许您向所有Array对象添加新propertiesmethods 。 我们可以为此目的创建一个原型

 Array.prototype.has_element = function(element) { return $.inArray( element, this) !== -1; }; 

然后像这样使用它

 var numbers= [1, 2, 3, 4]; numbers.has_element(3) => true numbers.has_element(10) => false 

请参阅下面的演示

 Array.prototype.has_element = function(element) { return $.inArray(element, this) !== -1; }; var numbers = [1, 2, 3, 4]; console.log(numbers.has_element(3)); console.log(numbers.has_element(10));