reverve
数组的倒序方法
Array.prototype.reverse = function(){
//用二分法
for(var i=0;i<this.length/2;i++){
//解构赋值
[this[i],this[this.length-1-i]] = [this[this.length-1-i],this[i]]
}
return this
}
slice
数组截取,不改变原数组,并把截取的新数组返回出去
Array.prototype.Slice =function(n=0,m=this.length){
if(n<=0&&m<0&&this.length+n>this.length+m){
return [];
}
n<0?n = this.length + n:n;
m<0?m = this.length + m:m;
m>this.length?m=this.length:m;
let res =[];
for(var i=n;i<m;i++){
res[res.length]=this[i];
}
return res;
}
concat
数组拼接,支持单个参数和数组
Array.prototype.concat=function(){
let res=[];
for(var j=0;j<this.length;j++){
res[res.length]=this[j]
}
for(var i=0;i<arguments.length;i++){
if({}.toString.call(arguments[i]) === '[object Array]'){
for(var z=0;z<arguments[i].length;z++){
res[res.length]=arguments[i][z]
}
}else{
res[res.length]=arguments[i]
}
}
return res;
}
sort
主要利用冒泡,不传参按照数字第一位排序,传参,a-b升序b-a倒序
Array.prototype.sort=function(compare){
//判断传入的是不是函数
if(typeof compare !== "function"&& compare !== undefined){
throw new Error( " The comparison function must be either a function or undefined" +
"at Array.sort (native)" );
}
for (var i = 0; i < this.length-1; i++) {
for (var j = 0; j < this.length-1-i; j++) {
//传入回调函数走这里
if(compare){
//a-b和b-a都是大于0才换位置
if(compare(this[j],this[j+1])>0){
[this[j],this[j+1]] = [this[j+1],this[j]]
}
//不传回调走这里,按首个数字排序
}else{
if((this[j]+"")[0] - (this[j+1]+"")[0] > 0 ){
[this[j],this[j+1]] = [this[j+1],this[j]]
}
}
}
}
}