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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11491405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:40:33  来源:igfitidea点击:

JS jQuery - check if value is in array

jqueryarraysvalidation

提问by Obmerk Kronen

I am more of a PHP person, not JS - and I think my problem is more a syntax problem ..

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

I have a small jQuery to "validate" and check input value .

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

It works ok for single words, but I need array.

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

I am using the inArray()of 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;
            });

        });

now - this if (jQuery.inArray(jQuery("input:first"), ar))is not working right .. every value that I put will be validated as OK . (even empty)

现在 - 这if (jQuery.inArray(jQuery("input:first"), ar))不正常......我输入的每个值都将被验证为 OK 。(甚至是空的)

I need to validate only values from the array (ar) .

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

I tried also if (jQuery.inArray(jQuery("input:first"), ar) == 1) // 1,0,-1 tried all

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

what am i doing wrong ?

我究竟做错了什么 ?

Bonus question : how to do NOT in array in jQuery ?? (the equivalent of PHP if (!in_array('1', $a))- I sw somehre that it will not work , and need to use something like this : !!~

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

回答by gion_13

You are comparing a jQuery object (jQuery('input:first')) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:

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

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

The inArraymethod returns -1if the element wasn't found in the array, so as your bonusanswer to how to determine if an element is notin an array, use this :

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

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

回答by Inkbug

As to your bonus question, try if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)

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

回答by Akxaya

Alternate solution of the values check

值检查的替代解决方案

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

回答by user3772550

The Array.prototypeproperty represents the prototype for the Arrayconstructor and allows you to add new propertiesand methodsto all Arrayobjects. we can create a prototype for this purpose

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

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

And then use it like this

然后像这样使用它

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

See the Demo below

看下面的演示

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));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>