JS中通过some方法和forEach遍历数组的区别
一、some() 方法
some() 方法用于检测数组中是否有满足指定条件的元素。
语法:array.some(function(currentValue,index,arr),thisValue)
返回值: 布尔值
let arr = [10, 20, 30, 40, 50]
let test = arr.some((item) => {
if (item === 30) {
console.log(item)
return item
}
})
console.log(test)
// 30
// true
二、forEach() 方法
forEach() 方法是让数组的每一项元素执行指定函数
语法:array.forEach(callbackFn(currentValue, index, arr), thisValue)
返回值: undefined
let arr = [10, 20, 30, 40, 50]
let test = arr.forEach((item) => {
console.log(item)
})
console.log(test);
// 10
// 20
// 30
// 40
// 50
// undefined
三、区别
- some() 中遇到 return 就可以终止循环
- forEach() 遇到 return 也不会终止循环,而是需要等到数组全部遍历才能终止
let arr = [10, 20, 30, 40]
arr.some((item) => {
console.log(item)
if (item == 20) {
console.log('找到元素退出循环')
return true // 找到元素后可以直接终止循环
}
})
// 10
// 20
// 找到元素退出循环
console.log('-------------------------------')
arr.forEach((item) => {
console.log(item)
if (item == 20) {
console.log('找到元素退出循环')
return true // 找到元素后继续遍历后续元素
}
})
// 10
// 20
// 找到元素退出循环
// 30
// 40