Home >Web Front-end >JS Tutorial >How to use lastIndexOf method

How to use lastIndexOf method

不言
不言Original
2019-02-20 16:05:238221browse

lastIndexOf() method can return the last occurrence position of a specified string value. If the second parameter start is specified, the specified position in a string will be searched from back to front. Let's take a closer look at how to use the lastIndexOf method.

How to use lastIndexOf method

Let’s first take a look at the basic syntax of lastIndexOf()

arr.lastIndexOf(searchElement[,index])

The first parameter of lastIndexOf() is searchElement. It is the value to search for in the array. The second parameter is the optional index, which defines the starting index in the array from which to search for elements backwards. If this parameter is not provided, index arr.length - is used as the starting index to start searching backwards, as it is the default value.

lastIndexOf() returns the index of the last occurrence of searchElement. If the element is not found in the array, this function returns -1.

Let’s look at a specific example

The function lastindexof() returns the last index where 2 appears, which is 0.

The code is as follows

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
<script> 
function func() { 
    var array = [2, 9, 9]; 
    document.write(array.lastIndexOf(2)); 
} 
func(); 
</script> 
</body>
</html>

Output result For: 0

The function lastindexof() finds the last occurrence of index 45. Because it doesn't exist, the function returns -1.

The code is as follows

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
<script> 
function func() { 
    var array = [2, 98, 12, 45]; 
    document.write(array.lastIndexOf(45,2)); 
} 
  
func(); 
</script>
</body>
</html>

The output result is: -1.

This article is all over here. For more exciting content, you can follow the php Chinese website Other related column tutorials! ! !

The above is the detailed content of How to use lastIndexOf method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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