forEach跟map函数区别在于map有返回值,forEach无返回值
map跟filter函数的区别在于filter会过滤值,而map直接返回值
filter跟some的区别在于some有符合的数据就返回true,而filter是返回值
some跟every的区别在于every要所有的数据都满足才返回true,而some是一个满足就返回true
上面几个函数的实现都差不多,只是某一小点不一样,其实原理都一样
//forEach
Array.prototype.myForEach = function(fn){
if(this === null){
throw new Error('对象为空')
}
if(typeof fn !== 'function'){
throw new Error('请传入函数!')
}
var o = this,
len = o.length >>> 0,
_this = arguments[1] || window;
for(var i = 0; i < len; i++){
fn.call(_this, o[i], i, o);
}
}
//map
Array.prototype.myMap= function(fn){
if(this === null){
throw new Error('对象为空')
}
if(typeof fn !== 'function'){
throw new Error('请传入函数!')
}
var o = this,
len = o.length >>> 0,
_this = arguments[1] || window,
res = [];
for(var i = 0; i < len; i++){
res.push(fn.call(_this, o[i], i, o));
}
return res;
}
//filter
Array.prototype.myFilter= function(fn){
if(this === null){
throw new Error('对象为空')
}
if(typeof fn !== 'function'){
throw new Error('请传入函数!')
}
var o = this,
len = o.length >>> 0,
_this = arguments[1] || window,
res = [];
for(var i = 0; i < len; i++){
if(fn.call(_this, o[i], i, o)){
res.push(o[i]);
}
}
return res;
}
//some
Array.prototype.mySome= function(fn){
if(this === null){
throw new Error('对象为空')
}
if(typeof fn !== 'function'){
throw new Error('请传入函数!')
}
var o = this,
len = o.length >>> 0,
_this = arguments[1] || window;
for(var i = 0; i < len; i++){
if(fn.call(_this, o[i], i, o)){
return true;
}
}
return false;
}
//every
Array.prototype.myEvery= function(fn){
if(this === null){
throw new Error('对象为空')
}
if(typeof fn !== 'function'){
throw new Error('请传入函数!')
}
var o = this,
len = o.length >>> 0,
_this = arguments[1] || window;
for(var i = 0; i < len; i++){
if(!fn.call(_this, o[i], i, o)){
return false;
}
}
return true;
}