数组的位置方法(indexOf和lastIndexOf)

数组类型有两个位置方法:indexOf和lastIndexOf。这两个方法都接收两个参数,要查找的项和(可选的)表示查找起点位置的索引。 indexOf 方法从数组开头(位置0)开始向后查找,lastIndexOf 方法则是从数组末尾向前查找。

这两个方法都返回要查找的项在数组中的位置,或者在没找到的情况下返回 -1。在比较第一个参数与数组中的每一项时,使用全等操作符(===)。

例如:

var colors = new Array("red", "blue", "green", "black", "blue","purple");
alert(colors.indexOf("blue"))		// 1
alert(colors.indexOf("blue", 2))	// 4
alert(colors.lastIndexOf("blue"))	// 4
alert(colors.indexOf("yellow"))	// -1
// 比较时全等
var str1 = new String("blue");
var str2 = "blue";
alert(typeof(str1))		// object
alert(typeof(str2))		// string
alert(colors.indexOf(str1))		// -1
alert(colors.indexOf(str2))		// 1
发布了23 篇原创文章 · 获赞 0 · 访问量 2656

猜你喜欢

转载自blog.csdn.net/xy405580364/article/details/103280177