JS jQuery - check if value is in array

后端 未结 4 1278
野的像风
野的像风 2021-02-05 07:05

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

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

It works ok

4条回答
  •  盖世英雄少女心
    2021-02-05 07:30

    The Array.prototype property represents the prototype for the Array constructor and allows you to add new properties and methods to all Array objects. we can create a prototype for this purpose

    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));

提交回复
热议问题