有时候遇到兼容问题,有的方法用不了,今天就some方法自己来实现一个,方便使用。
some()
方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值,如果通过了则返回true,未通过返回false。
下面看代码:
var arr = [1,2,25,100,60,37]
Array.prototype.mySome=function(callback){
//如果没有传入回调函数,则报错
if(!callback) throw new TypeError('undefined is not a function');
if (typeof callback !== 'function') {//传入的不是函数也报错
throw new TypeError(callback + " is not a function");
}
for(var i=0,len=this.length;i<len;i++){
if(callback(this[i],i,this)){//如果回调函数的返回值为true ,则终止循环,返回true
return true;
}
}
return false;//最终没有匹配到就返回false
}
var ret=arr.mySome(function(item,index,thisArr){
console.log(item,index,thisArr);
return item>10
});
console.log(ret);
测试一下:
1 0 (6) [1, 2, 25, 100, 60, 37]
2 1 (6) [1, 2, 25, 100, 60, 37]
25 2 (6) [1, 2, 25, 100, 60, 37]
true
看到数组的第3个元素25是大于10的,不需要遍历所有元素,看到打印了3次便跳出,并打印最终的返回true,目前看来是达到了预期的效果。
再来测试一下不传参数:
var arr = [1,2,25,100,60,37]
Array.prototype.mySome=function(callback){
//如果没有传入回调函数,则报错
if(!callback) throw new TypeError('undefined is not a function');
if (typeof callback !== 'function') {//传入的不是函数也报错
throw new TypeError(callback + " is not a function");
}
for(var i=0,len=this.length;i<len;i++){
if(callback(this[i],i,this)){//如果回调函数的返回值为true ,则终止循环,返回true
return true;
}
}
return false;//最终没有匹配到就返回false
}
var ret=arr.mySome();
console.log(ret);
输出:
Uncaught TypeError: undefined is not a function
然后再测传入的不是函数:
var arr = [1,2,25,100,60,37]
Array.prototype.mySome=function(callback){
//如果没有传入回调函数,则报错
if(!callback) throw new TypeError('undefined is not a function');
if (typeof callback !== 'function') {//传入的不是函数也报错
throw new TypeError(callback + " is not a function");
}
for(var i=0,len=this.length;i<len;i++){
if(callback(this[i],i,this)){//如果回调函数的返回值为true ,则终止循环,返回true
return true;
}
}
return false;//最终没有匹配到就返回false
}
var ret=arr.mySome(11);
console.log(ret);
输出:
Uncaught TypeError: 11 is not a function
可以看到能够正常的检测出没有传回调函数或者回调不是Function的情况。
测试空数组的话,一直返回false,完成收工!