pop 方法
var arr=[1,7,4,9,3];
Array.prototype.ppop = function () {
var arr = this;
arr.length--;
return arr;
};
console.log(arr.ppop());
push 方法
var arr = [1, 7, 4, 9, 3];
Array.prototype.ppush = function (value) {
this[this.length] = value;
return this;
};
console.log(arr.ppush(2));
slice 方法
var arr = [1, 7, 4, 9, 3];
Array.prototype.sslice = function () {
var star = arguments[0] < 0 ? this.length + arguments[0] : arguments[0];
var end = arguments[1] < 0 ? this.length + arguments[1] : arguments[1];
var newArray = [];
newArray.length = end - star;
for (var i = star, j = 0; i < end; i++, j++) {
newArray[j] = this[i];
}
return newArray;
};
console.log(arr.sslice(-3, -1));
splice方法
备注:这个实现比起 pop ,push 略有复杂,应该是数组方法中最难的方法了。
var arr = [1, 7, 4, 9, 3];
Array.prototype.ssplice = function () {
var dele = [];
dele.length = arguments[1];
var arr = this;
//删除指定元素
for (var i = 0, key = arguments[0]; i < arguments[1]; i++, key++) {
dele[i] = arr[key];
arr[key] = arr[key + arguments[1]];
}
arr.length -= arguments[1];
var addCount = arguments.length - 2;
//移动位置为添加的元素预留位置
arr.length += addCount;
for (var move = arr.length - 1; move > arr.length - addCount - arguments[0]; move--) {
arr[move] = arr[move - addCount];
}
//添加新元素
for (var addArr = arguments[0], newNumber = 2; addArr < addCount + arguments[0]; addArr++, newNumber++) {
arr[addArr] = arguments[newNumber];
}
return dele;
};
console.log(arr.ssplice(2, 2, 6, 4));
console.log(arr);