# 重写数组的方法（改变原数组）

2021/11/16 16:06

## 改变原数组的方法

push()

var color = ['red', 'green']
var color2 = color2.push(['blue','purple'])

alert(color)    // ['red', 'green']
alert(color2)    // ['red', 'green','blue','purple']


Array.prototype._push = function() {
for(let i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i]
}
return this.length
}

var arr1 = [1, 2, 3]
console.log(arr1.push(4, 5))    // 返回新数组的长度  5
console.log(arr1._push(6, 7))   // 返回新数组的长度  7
console.log(arr1)    // [1, 2, 3, 4, 5, 6, 7]


pop()

var color = ['red', 'green','blue','purple']
var color2 = color.pop()


Array.prototype._pop() = function() {
if(this.length) {
let res = this[this.length - 1]
delete this[this.length]
this.length--
return res
}
}

let arr2 = [1, 2, 3, 4, 5]
console.log(arr2.pop())    // 返回删除的元素 5
console.log(arr2._pop())    // 返回删除的元素 4
console.log(arr2)    // [1, 2, 3]


sort()

let values = [0, 1, 5, 10, 15]
values.sort()
console.log(values)   //0,1,10,15,5


function compare(a, b) {
if(a < b) return -1
else if(a > b)  return 1
else return 0
}


let values = [0, 1, 5, 10, 15]
values.sort(compare)
console.log(values)   // 0,1,5,10,15


function compare(a, b) {
if(a < b) return 1
else if(a > b)  return -1
else return 0
}

let values = [0, 1, 5, 10, 15]
values.sort(compare)
console.log(values)   // 15,10,5,1,0


var arr = [4, 1, 6, 9, 3, 2, 8, 7]
var arr2 = [4, 1, 6, 9, 3, 2, 8, 7]
console.log(arr.sort());

Array.prototype.mySort = function (arr) {
for (var i = 0; i < this.length; i++) {
for (var j = i + 1; j < this.length; j++) {
if (this[i] > this[j]) {
var temp = this[i]
this[i] = this[j]
this[j] = temp;
}
}
}
return this
}

console.log('mySort:',arr2.mySort());


reverse()


Array.prototype.myReverse = function () {
var left = 0,
right = this.length - 1;

while (left < right) {
var temp = this[left];
this[left] = this[right];
this[right] = temp;
left++;
right--;

}
}
var arr2 = [1, 3, 5, 7, 9]
console.log('before:', arr2)
myReverse(arr2)
console.log('after:', arr2)


shift()

var arr = [1, 3, 5, 7]
console.log(arr.unshift(9))
console.log(arr)

Array.prototype.myUnshift = function () {
var L = this.length;
var newArr = arguments.length
for (var i = L + newArr - 1; i >= 0; i--) {
if (i > newArr - 1) {
this[i] = this[i - newArr];
} else {
this[i] = arguments[i];
}
}
return this.length;
}

var arr2 = [1, 3, 5, 7,]

console.log('myUnshift:', arr2.myUnshift(9));
console.log('myUnshift:', arr2)


unshift()

var arr = [1, 3, 5, 7]
console.log(arr.unshift(9))
console.log(arr)

Array.prototype.myUnshift = function () {
var L = this.length;
var newArr = arguments.length
for (var i = L + newArr - 1; i >= 0; i--) {
if (i > newArr - 1) {
this[i] = this[i - newArr];
} else {
this[i] = arguments[i];
}
}
return this.length;
}

var arr2 = [1, 3, 5, 7,]

console.log('myUnshift:', arr2.myUnshift(9));
console.log('myUnshift:', arr2)


#### 推荐阅读

Python Type Hints 从入门到实践

0
0 收藏

1 评论
0 收藏
0