some方法其实可以解释为把所有的项执行callback,只要有其中一个返回true
整个结果就返回true
定义:some() 方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。
在网上主要的实现有两种
第一种
Array.prototype.some = function (cb) {
for (let i = 0; i < this.length; i++) {
if (cb && cb(this[i], i, this) {
return true
}
}
return false
}
第二种
Array.prototype.some = function (cb) {
let result = false
for (let i = 0; i < this.length; i++) {
result = cb && cb(this[i], i, this)
}
return result
}
其中区别在于,调用的数组循环了多少次
- 方法一:只要
true
就立即return
,不会循环完所有的项 - 方法二:所有项都遍历完,时间复杂度为O(n)
而实际上测试:
some
循环时,只要遇到了true
就立即返回,所以第二种写法是错的,这一点小细节需要注意