javascript lastindexof()怎么用

文章2022-03-2395 人已阅来源:网络

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

javascript lastindexof()怎么用

本教程操作环境: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"));  //4
console.log(a.lastIndexOf("cd", 2));  //1
console.log(a.lastIndexOf("gh"));  //-1
console.log(a.lastIndexOf("ab", -3));

javascript lastindexof()怎么用

示例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 lastindexof()怎么用

【相关推荐:javascript学习教程

以上就是javascript lastindexof()怎么用的详细内容!