In javascript, lastindexof() is used to find elements in an array. It can return the last position (subscript value) of the specified element value in the array. The syntax is "array.lastIndexOf(item,start)" ; If the return value is "-1", the specified element does not exist in the array.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In JavaScript, the lastindexof() method is used to find elements in an array.
The lastindexof() method returns the last position (subscript value or index value) of a specified element in the array. If the element to be retrieved does not appear, the method returns -1
.
Therefore, you can use the lastindexof() method to determine whether the specified value exists in the array.
Grammar:
array.lastIndexOf(item,start)
item Required. Specifies the string value to be retrieved.
#start Optional integer parameter. Specifies the position in the string to begin searching. Its legal values are 0 to stringObject.length - 1. If this parameter is omitted, the search will start from the last character of the string.
The lastindexof() method will retrieve the specified element item in the array from end to end. The position to start retrieval is at the start of the array or the end of the array (when the start parameter is not specified). If an item is found, the position of the first occurrence of item in the array is retrieved from the end to the front. The index of the array starts from 0.
Example 1:
var a = ["ab","cd","ef","ab","cd"]; console.log(a.lastIndexOf("cd")); //4 console.log(a.lastIndexOf("cd", 2)); //1 console.log(a.lastIndexOf("gh")); //-1 console.log(a.lastIndexOf("ab", -3));
Example 2: Determine whether the specified value exists
var a = ["ab","cd","ef","ab","cd"]; var b="cd"; if(a.lastIndexOf(b)==-1){ console.log("元素不存在"); }else{ console.log("元素存在"); } var b="gh"; if(a.lastIndexOf(b)==-1){ console.log("元素不存在"); }else{ console.log("元素存在"); }
【 Related recommendations: javascript learning tutorial】
The above is the detailed content of How to use javascript lastindexof(). For more information, please follow other related articles on the PHP Chinese website!