In jQuery, you can use the $.inArray()
method to check if an array includes a particular value or not. Here's an example:
javascriptconst arr = ['apple', 'banana', 'orange', 'grape'];
console.log($.inArray('orange', arr) !== -1); // Output: true
console.log($.inArray('mango', arr) !== -1); // Output: false
In this example, the $.inArray()
method is used to check if the arr
array includes the values 'orange'
and 'mango'
.
The $.inArray()
method takes two arguments: the value to check for in the array, and the array itself. If the value is found in the array, the method returns the index of the value in the array (which will be a non-negative integer), otherwise it returns -1
.
To check if a value is present in the array, we can compare the result of $.inArray()
to -1
using the inequality operator !==
. If the result is not equal to -1
, it means the value is present in the array, otherwise it is not.
In the first console.log()
statement, the $.inArray()
method returns the index 2
, which is not equal to -1
, so the output is true
because the value 'orange'
is present in the arr
array. In the second console.log()
statement, the $.inArray()
method returns -1
, which is equal to -1
, so the output is false
because the value 'mango'
is not present in the arr
array.
JQuery, JQuery Tutorial, jQuery Interview Question and Answers
Comments
Post a Comment