21
4

4 回答 4

55

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:

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

The inArray method returns -1 if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :

if(jQuery.inArray(el,arr) == -1){
    // the element is not in the array
};
于 2012-07-15T11:18:48.177 回答
1

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

于 2012-07-15T11:20:34.907 回答
0

Alternate solution of the values check

//Duplicate Title Entry 
    $.each(ar , function (i, val) {
        if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
  });
于 2015-01-29T20:27:50.850 回答
-1

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

于 2018-01-09T20:36:05.267 回答