Judgment method: 1. Use indexOf() method, syntax "arr.indexOf(value to be found)"; 2. Use "arr.find()" method; 3. Use "array.findIndex( )" method; 4. Use the "$.inArray('value to be found', arr)" method.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Js determines whether an element exists in the array
Method 1: indexOf(item,start);
Item: The value to be searched;
start: Optional integer parameter, the default is to start searching from the starting position.
indexOf(); Returns the position of the element in the array, if not, returns -1;
Example: var arr=['aaa','bbb' ,'ccc','ddd','eee'];
1 2 3 4 |
|
My usual usage: if(arr.indexOf(element to be found)>-1){Operation for element existence};
indexOf() cannot find NaN
Method 2: arr.find();
The parameter of Arr.find() is a callback function. All elements of the array will traverse this callback function until the first element with a return value of true is found, and then return the element, otherwise return undefined;
1 2 3 4 5 |
|
My usual usage:
1 2 3 4 5 |
|
Method 3: array.findIndex();
findIndex() and find() are similar in usage. find() returns the element, and findIndex returns the position of the element. findIndex(); returns the position of the first array element that meets the conditions. If all elements do not meet the conditions, it returns -1; findIndex(), each element in the array will call the function once, but when the condition returns true, findIndex() returns the position of the element that meets the conditions, and the execution function will not be called for subsequent values.
1 2 3 4 5 |
|
Description: findIndex() and find() can be used to find NaN;
1 2 3 4 5 |
|
Method 4:
Use jquery’s inArray method, This method returns the subscript of the element in the array. If it does not exist in the array, then returns -1;
1 2 3 |
|
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to determine whether an element exists in a javascript array. For more information, please follow other related articles on the PHP Chinese website!