温馨提示  2024年 6月我们已经停止开发者板块文章内容更新,谢谢来访。存档数据
知识 2023-08-24 39 次阅读

javascript lastindexof()怎么用

   

在javascript中,lastindexof()用于在数组中查找元素,可返回指定元素值在数组中最后出现的位置(下标值),语法“array.lastindexof(item,start)”;如果返回值为“-1”,则指定元素不存在数组中。

本教程操作环境windows7系统、javascript1.8.5版、dell g3电脑。

在javascript中,lastindexof()方法用于在数组中查找元素。

lastindexof()方法可返回一个指定的元素在数组中最后出现的位置(下标值或索引值)。如果要检索的元素没有出现,则该方法返回-1。

所以呢,可以利用lastindexof()方法判断指定值在数组中是否存在。

语法

array.lastindexof(item,start)

item 必需。规定需检索的字符串值。

start 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringobject.length - 1。如省略该参数,则将从字符串的最后一个字符处开始检索。

lastindexof()方法将从尾到头地检索数组中指定元素 item。开始检索的位置在数组的 start 处或数组的结尾(没有指定 start 参数时)。如果找到一个 item,则返回 item 从尾向前检索第一个次出现在数组的位置。数组的索引开始位置是从 0 开始的。

示例1

var a = [ab,cd,ef,ab,cd];console.log(a.lastindexof(cd)); //4console.log(a.lastindexof(cd, 2)); //1console.log(a.lastindexof(gh)); //-1console.log(a.lastindexof(ab, -3));

示例2判断指定值是否存在

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(元素存在);}

【相关推荐javascript学习教程】