lastIndexOf方法如何使用

  介绍

这篇文章给大家分享的是有关lastIndexOf方法如何使用的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

lastIndexOf()方法可返回一个指定的字符串值最后出现的位置,如果指定第二个参数,则在一个字符串中的指定位置从后向前搜索。下面我们就来具体看看lastIndexOf方法的使用方法。

我们先来看一下<强> lastIndexOf()的基本语法

arr.lastIndexOf (searchElement[、索引])

lastIndexOf()的第一个参数是searchElement,它是要在数组中搜索的值。第二个参数是可选的指数,它定义数组中的起始索引,从中向后搜索元素。如果未提供此参数,则将arr指数。长度,作为开始向后搜索的起始索引,因为它是默认值。

lastIndexOf()返回searchElement最后一次出现的索引。如果在数组中找不到该元素,则此函数返回1 .

下面我们来看具体示例

函数lastIndexOf()返回出现2的最后一个索引,即0。

代码如下

& lt; !DOCTYPE html>   & lt; html>   & lt; head>   & lt; title> & lt;/title>   & lt;/head>   & lt; body>   & lt; script>   函数func () {   var数组=(2、9、9);   document . write (array.lastIndexOf (2));   }   func ();   & lt;/script>   & lt;/body>   & lt;/html>

输出结果为:0

函数lastindexof()查找最后出现的索引45岁。因为它不存在,所以函数返回1 .

代码如下

& lt; !DOCTYPE html>   & lt; html>   & lt; head>   & lt; title> & lt;/title>   & lt;/head>   & lt; body>   & lt; script>   函数func () {   数组var=(98, 12日45);   document . write (array.lastIndexOf(45岁,2));   }      func ();   & lt;/script>   & lt;/body>   & lt;/html>

输出结果为:1。

感谢各位的阅读!关于lastIndexOf方法如何使用就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

lastIndexOf方法如何使用