indexOf方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在则返回-1。
一、查元素所在的位置(查找数组项,返回对应的下标)
该方法将从头到尾地检索数组,看它是否含有对应的元素。开始检索的位置在数组 start 处或数组的开头(没有指定 start参数时)。如果找到一个 item,则返回 item 的第一次出现的位置。
let food= ["番茄", "胡萝卜", "排骨", "苹果"];
let a = food.indexOf("苹果");
console.log(a)// 3
二、某元素在数组中出现的次数;
例子:查找 ’abcosidfnoiojisoo’ 中所有o出现的位置以及次数;
var str = ’abcosidfnoiojisoo',
var index = str.indexOf('o');
var num = 0;
while(index !== -1) {
console.log(index);
num++;
index = str.indexOf('red', index + 1);
}
例子:查找 ’abcosidfnoiojisoo’ 中所有o出现的位置以及次数;
var str = [];
searchNum(){
str.forEach((item)=>{
if(str.indexOf(item)!==-1){
console.log(index);
num++;
index = str.indexOf('red', index + 1);
}
})
}
三、循环数组实现去重;
var result = [];
uniqueArray() {
result .forEach(function(item) {
if(result.indexOf(item) === -1) {
result .push(item);
}
})
}
四、使用ES6的Set对象去重
var myArray = [1, 2, 2, 3, 4, 4, 5];
myArray =. [...new Set(arr)]