In the previous article, we learned how to use includes() to determine whether an array contains a specified value. Please see "How to use includes() in js to determine whether an array contains a specified value". This time we will learn about the method of returning the end index of a specified element. You can refer to it if necessary.
Let’s look at a small example first.
We now have such a problem. It is known that we have an array containing one, two, three, one, two. Now we want to know the index of the last occurrence of the element three in this array. What? What about the element one and the element two?
<script> var arr = new Array(7); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; arr[3] = "one"; arr[4] = "two"; console.log(arr.lastIndexOf('three')); console.log(arr.lastIndexOf('one')); console.log(arr.lastIndexOf('two')); </script>
The result of this example is
In this example, we count the position where three last appeared. Whether it is three, the index of the element three is 2; by analogy, it can be concluded that the index of the element one is 3, and the index of the element two is 4.
After knowing this, let’s take a look at the lastIndexOf method.
lastIndexOf() method returns the last index of the specified element (that is, a valid JavaScript value or variable) in the array, or -1 if it does not exist. Search from the back of the array forward, starting from the search position.
Let’s take a look at the syntax of this method.
数组名称.lastIndexOf(被查找的元素,查询位置)
The second parameter in this method represents the reverse search starting from this position. The default is the length of the array minus 1(arr.length - 1)
, that is, the entire array is searched. If the value is greater than or equal to the length of the array, the entire array is searched. If negative, treat it as an offset forward from the end of the array. Even if the value is negative, the array will still be searched from back to front. If the value is negative and its absolute value is greater than the length of the array, the method returns -1, that is, the array will not be searched.
That’s all. If you need it, you can read: javascript advanced tutorial
The above is the detailed content of How to return the end index of a specified element in javascript. For more information, please follow other related articles on the PHP Chinese website!