JS的语法中,有许多可以对数组进行遍历的操作,比如forEach、some、map、filter、some、every、reduce、reduceRight等方法,但不同场景下使用的方法也不一样,对于数组遍历而言,我们更偏爱于forEach方法,因为操作简单,能满足大部分的场景需求,但如果我们实际需求中只需要遍历到需要的数据时就立马跳出循环时,使用some方法可能更合适。
先给出结论:对数组进行唯一元素的查询,建议使用some方法,因为这个方法相比于forEach方法能在查找数组元素的过程中,一旦匹配到需要的元素,可以立马跳出循环,节省内存空间,降低时间损耗,实例如下:
使用forEach()方法
const Arr = ['red','green','blue','black'];
Arr.forEach(function(value){
if(value == 'green'){
console.log('成功找到green!')
return true
}
console.log(value)
})
使用some()方法
const Arr = ['red','green','blue','black'];
Arr.some(function(value){
if(value == 'green'){
console.log('成功找到green!')
return true
}
console.log(value)
})
显而易见,如果用forEach方法,使用return语句不能返回到外层函数。而some方法能在匹配到相应的条件时,能根据return true这个语句直接跳出当前循环,缩短运行时间。