一、length
//在尾部新增任意多个数据
//1.线性结构的代码
var arr=[100,200,300,400];//length:4
arr[arr.length] = 500;//arr[4]=500 arr.length=5
arr[arr.length] = 600;//arr[5]=600 arr.length=6
//2.函数 代码的复用
function myAdd(){
//内部实际参数的变量arguments
//this指代的是arr数组
for(var key in arguments){
var value = arguments[key];
this[this.length] = value;//14行代码
}
}
var arr4=[100,200];
//arr4.myAdd(300,400,500,600)
myAdd.call(arr4,300,400,500,600);
console.log(arr4,arr4.length);
//反建立函数与对象
myAdd.apply(arr4,[700,800,900]);
console.log(arr4,arr4.length);
//3.原型方法新增
console.log(Array.prototype);//arr4的父亲
console.log(Array.prototype.proto)//arr4的父亲内部的变量 属性的访问
Array.prototype.age = 100;
console.log(Array.prototype);
Array.prototype.myAdd = myAdd;
console.log(Array.prototype);
arr4.myAdd(‘ab’);
console.log(arr4);
//删除数组尾部数据,返回删除的单个数据
Array.prototype.myRm=function(){
//this指代的就是Array构造的对象 max=this.length-1
var value=this[this.length-1];
this.length–;
//var value=this[this.length-- -1];后置–的原理,执行语法报错
return value;
}
console.log(arr4.myRm());
console.log(arr4.myRm(),arr4.length);
//在头部新增任意多个数据,并且返回最终数组长度
Array.prototype.myHeadAdd=function(){
//1.新增的值依次做插入操作
// 1.1新增长度值+1
// 1.2后序遍历 1~max
// 1.2.1 当前空间=前一个空间的值
// arr[i] = arr[i-1]
// 1.3 arr[0]=新增的值
//for(var key in arguments){//1.
for(var key=arguments.length-1;key>=0;key–){
var newvalue=arguments[key];
this.length++;//this.length=this.length+1; 1.1
for(var i=this.length-1;i>=1;i–){//1.2
this[i] = this[i-1];
}
this[0] = newvalue;
}
return this.length;
}
arr4.myHeadAdd(‘hello’);
console.log(arr4);
arr4.myHeadAdd(‘briup’,22.22,‘abc’);
console.log(arr4);
//在数组的头部删除数据,返回删除的单个值
Array.prototype.myHeadRm=function(){
//1.re=arr[0]
//2.正序遍历数组,将arr[i] = arr[i+1] 0~max-1
//3.长度-1
var result = this[0];
var i=0;
while(i<this.length-1){
this[i]=this[i+1];
i++;
}
this.length–;
return result;
}
console.log(arr4.myHeadRm());//briup
console.log(arr4.myHeadRm());//22.22
console.log(arr4.myHeadRm());//abc
console.log(arr4);//hello 100~800
二、排序
1.ar arr1=[3,4,2,6,1];
var result=arr1.sort();
console.log(result);//1,2,3,4,5,6
console.log(arr1);//1,2,3,4,5,6
var arr2=[10,1,23,2];
//console.log(arr2.sort());
arr2.sort();
console.log(arr2);//1,10,2,23
console.log(arr1.reverse());
console.log(arr2.reverse());
2.function compare(v1,v2){
//大于0 小于0 等于0
return v1-v2;
}
arr2.sort(compare);
console.log(arr2);
arr2.reverse(compare);
console.log(arr2);