The indexof() method in javascript is used to find the specified element in the array. It can return the index of the first match of the specified element value in the array. If the specified value is not found, it returns "-1 "; Using this feature, this method can also be used to determine whether the specified element exists in the array.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript indexOf() returns the index of the first match of an element value in the array, or -1 if the specified value is not found. Usage is as follows:
array.indexOf(searchElement[, fromIndex]);
Parameter description:
array: Represents an array object.
searchElement: Required parameter, the value to be located in the array.
fromIndex: Optional parameter, array index used to start the search. If this parameter is omitted, the search starts at index 0. If fromIndex is greater than or equal to the array length, -1 is returned. If fromIndex is negative, the search begins at the length of the array plus fromIndex.
indexOf() method performs a search in ascending index order, that is, retrieving from left to right. When retrieving, the array elements will be compared congruently with the searchElement parameter value ===.
Example 1: Return the position where the specified element first appears. If not found, return -1
var a = ["ab","cd","ef","ab","cd"]; console.log(a.indexOf("cd")); //1 console.log(a.indexOf("cd", 2)); //4 console.log(a.indexOf("gh")); //-1 console.log(a.indexOf("ab", -2)); //3
Output result:
Example 2: Use the indexOf() method to determine whether the specified element exists, [For more judgment methods, you can read the article "JS array learning to check whether it is The given element exists 》】
var a = ["ab","cd","ef","ab","cd"]; var b = a.indexOf("cd"); if (b>0) { console.log("给定元素是存在的"); } else { console.log("给定元素是不存在的"); }
Output result:
[Recommended learning: javascript advanced tutorial】
The above is the detailed content of What is the use of javascript indexof method?. For more information, please follow other related articles on the PHP Chinese website!