.indexOf()
方法可以返回数组中第一次匹配元素的下标,如果不存在则返回 -1。
另外 [[lastIndexOf]] 可以查找数组中最后一次出现的元素下标。
语法
indexOf(searchElement)indexOf(searchElement, fromIndex)
- searchElement: 要查找的元素
- fromIndex: 开始查找的索引(会忽略指定索引前所有元素)
使用
const colors = ['red', 'blue', 'yellow', 'green'];
console.log(colors.indexOf("blue")) // 2console.log(colors.indexOf("blue", 3)) // -1