重写数组的API

pop方法删除数组的最后一个元素,并返回这个元素
var arr = [1,3,5,7,9];
Array.prototype.mypop=function(){
var lastchild=this[this.length-1];
if(this.length==0){
return undefined;
}
else{
this.length–;
}
return lastchild;
}
var a = arr.mypop();
console.log(a,arr)

push方法向数组末尾添加一个或多个元素,并返回新数组的长度
var arr = [1,3,5];
Array.prototype.mypush=function(){
var newlength=this.length+arguments.length;
for(i=0;i<arguments.length;i++){
this[newlength-arguments.length+i]=arguments[i];
}
return newlength;
}
var a = arr.mypush(7,9);
console.log(a,arr);

shift方法删除数组第一个元素 并返回被删除元素的值
var arr = [1,3,5,7,9]
Array.prototype.myshift=function(){
var result = this[0];
for(i=0;i<this.length;i++){
this[i]=this[i+1];
}
this.length–;
return result;
}
var a = arr.myshift();
console.log(a,arr);

UNshift方法向数组的开头添加一个或多个元素 并返回数组的长度
var arr = [1,3,5];
Array.prototype.myunshift=function(){
var newlength = this.length+arguments.length;
for(i=0;i>newlength;i–){
if(i>arguments.length){
this[i]=this[i-arguments.length]
}
else{
this[i]=arguments[i];
}
}
return newlength;
}
var a = arr.unshift(5,8,9,4,2,5);
console.log(a,arr);

every方法判断数组中的元素是否全部满足条件 返回值为true和false
var arr = [1,-3,5,6];
Array.prototype.myevery=function(foo,obj){
for(i=0;i<this.length;i++){
if(!(obj?foo.bind(obj)(this[i]) :foo(this[i])))
{
return false;
}
}
return true;

}
//方法的调用需要传参
var result = arr.myevery(function(item,index){
console.log(this);
return item>0;
},
“a”)
console.log(result);

some;判断数组中是否有元素满足条件 有一个满足条件 返回值都是true
var arr = [1,3,5,7];
Array.prototype.mysome=function(foo,obj){
for(i=0;i<this.length;i++){
if(obj?foo.bind(obj)(this[i]):foo(this[i])){
return true;
}
}
return false;
}
var result = arr.mysome(function(item,index){
console.log(this);
return item > 5;
},
“a”)
console.log(result);

map:返回一个新数组 对数组内的所有数进行操作
var arr = [1,3,5,7];
Array.prototype.mymap=function(foo,obj){
var newArr=[];
for(i=0;i<this.length;i++){
newArr[i]=(obj?foo.bind(obj)(this[i]):foo(this[i]));
}
return newArr;
}
var a = arr.map(function(item,index){
console.log(this);
return item+1;
},“a”)
console.log(a);

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
var arr = [1,3,5,7];
Array.prototype.myfilter=function(foo,obj){
var newresult=[];
var j = 0;
for(i=0;i<this.length;i++){
if(obj?foo.bind(obj)(this[i]):foo(this[i])){
newresult[j++]=this[i];
}
}
return newresult;

}
var a = arr.myfilter(function(item,index){
console.log(this);
return item>2;

},
“a”
)
console.log(a);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值