Home > Web Front-end > JS Tutorial > body text

What is the use of javascript indexof method?

青灯夜游
Release: 2023-01-07 11:46:29
Original
10768 people have browsed it

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.

What is the use of javascript indexof method?

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]);
Copy after login

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
Copy after login

Output result:

What is the use of javascript indexof method?

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("给定元素是不存在的");
}
Copy after login

Output result:

What is the use of javascript indexof method?

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template