# 干货：数组方法的仿写

## 这里提到一个新的知识点：Array.prototype.*;

Array.prototype.uName = “都是数组”;

Array.prototype.sum = function(){

// console.log(“这是新加的函数”,this);

var sum = 0;

for (var i = 0; i < this.length; i++) {

sum+=this[i];

}

return sum;

}

var a = [1,2,3];

var b = [4,5,6];

console.log(a.uName);

console.log(b.uName);

console.log(a.sum());

console.log(b.sum());

## 仿写数组方法

// 给所有的数组对象添加myPush方法

Array.prototype.myPush = function(){

// 哪个数组对象调用myPush,this就指向调用myPush的数组对象

console.log(this);

// 调用的时候写了多少个参数，arguments就有几个元素，arguments是所有参数组成的数组，称之为参数列表

console.log(arguments);

for (var i = 0; i < arguments.length; i++) {

this[this.length] = arguments[i];

}

}

a.myPush(3,45,5);

console.log(a);

Array.prototype.myPop = function(){

var res = this[this.length-1];

this.length = this.length-1;

return res;

}

a.myPush(44,55,66,77,88);

// a.myPop();

console.log(a.myPop());

Array.prototype.myReverse = function(){

for (var i = 0; i < parseInt(this.length/2); i++) {

// this[i] = this[this.length-1-i];

var temp = this[i];

this[i] = this[this.length-1-i];

this[this.length-1-i] = temp;

}

}

console.log(a);

a.myReverse();

console.log(a);

Array.prototype.myUnshift = function(){

this.myReverse();

for (var i = arguments.length – 1; i >=0; i–) {

this.myPush(arguments[i]);

}

this.myReverse();

}

a.myReverse();

a.myUnshift(100,200);

console.log(a);

Array.prototype.myShift = function(){

this.myReverse();

var res = this.myPop();

this.myReverse();

return res;

}

a.myShift();

console.log(a);

join

Array.prototype.myJoin = function(str){

// if(str===undefined){

// str = “,”;

// }

// var all = “”;

// for (var i = 0; i < this.length-1; i++) {

// all = all+this[i]+str;

// }

// all+=this[this.length-1];

// return all;

var all = this[0];

for (var i = 1; i < this.length; i++) {

all = all+str+this[i];

}

return all;

}

console.log(a.myJoin(“-“));

Array.prototype.mySplice = function(index,length){

var arr =[];//存放拼接的新数组

var resArr = [];//作为返回值返回

// 把index-length范围的数做成数组，作为mySplice的返回值

for (var i = index; i < index+length; i++) {

resArr.myPush(this[i]);

}

// 拼接新的数组分为三部分

// 1.范围之前的，即index之前的

for (var i = 0; i < index.length; i++) {

arr.myPush(this[i]);

}

// 2.参数列表里面下标为2(包括2)之后的参数

for (var i = 2; i < arguments.length; i++) {

arr.myPush(arguments[i]);

}

// 3.范围之后的所有数据

for (var i = index+length; i < this.length; i++) {

arr.myPush(this[i]);

}

// arr 新数组赋值给this

this.length =0;

for (var i = 0; i < arr.length; i++) {

this[i] = arr[i];

}

return resArr;

}

var a= [1,2,34,5];

a.mySplice(0,2,3);

console.log(a);

|