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

Obm*_*nen 21 arrays validation jquery

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

我有一个小jQuery来"验证"并检查输入值.

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

我正在使用 inArray()jQuery.

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("<span>VALUE FOUND</span>").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;
            });

        });
Run Code Online (Sandbox Code Playgroud)

现在 - 这if (jQuery.inArray(jQuery("input:first"), ar)) 是行不通的..我放的每个值都会被验证为OK.(甚至是空的)

我只需要验证数组中的值(ar).

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

我究竟做错了什么 ?

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

gio*_*_13 55

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

if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)
Run Code Online (Sandbox Code Playgroud)

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

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