一、mypop
Array.prototype.myPop = function () {
var temp = this[this.length - 1];
this.length--
return temp
}
var arr = [1, 2, 3, 4, 5];
console.log(arr);
var result = arr.myPop();
console.log(result);
console.log(arr)
二、myPush
Array.prototype.myPush = function () {
for (var i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i]
}
return this.length
}
var arr = [1, 2, 3, 4, 5];
console.log(arr);
var result = arr.myPush('hello');
console.log(result);
console.log(arr);
三、myShift
Array.prototype.myShift = function () {
var result = this[0];
for (i = 0; i < this.length; i++) {
this[i] = this[i + 1]
}
this.length--
return result
}
var arr = [1, 2, 3, 4, 5];
console.log(arr);
var result = arr.myShift();
console.log(result);
console.log(arr);
四、myUnshift
Array.prototype.myUnshift = function () {
var sum = this.length + arguments.length;
for (var i = sum; i > 0; i--) {
if (i > arguments.length) {
this[i - 1] = this[i - 1 - arguments.length]
} else {
this[i - 1] = arguments[i - 1]
}
}
return sum
}
var arr = [1, 2, 3];
console.log(arr);
var result = arr.myUnshift('hello', 'a', 'b');
console.log(result);
console.log(arr);
五、myForEach
Array.prototype.myForEach = function (fun) {
for (var i = 0; i < this.length; i++) {
fun(this[i], i, this)
}
}
var arr = [1, 2, 3];
console.log(arr);
var result = arr.myForEach(function (item, index, arr) {
console.log(item, index, arr)
});
六、myEvery
Array.prototype.myEvery = function (fun, obj) {
for (var i = 0; i < this.length; i++) {
if (!(obj ? fun.bind(obj)(this[i]) : fun(this[i]))) {
return false
}
}
return true
};
var arr = [1, 2, 3, 4, 5];
var result = arr.myEvery(function (item, index, arr) {
console.log(this)
return item > 1
}, { name: 'zhangsan' })
console.log(result)
七、mySome
Array.prototype.mySome = function (fun, obj) {
for (var i = 0; i < this.length; i++) {
if ((obj ? fun.bind(obj)(this[i]) : fun(this[i]))) {
return true
}
}
return false
};
var arr = [1, 2, 3, 4, 5];
var result = arr.mySome(function (item, index, arr) {
console.log(this)
return item > 1
}, { name: 'zhangsan' })
八、myMap
Array.prototype.myMap = function (fun, obj) {
var result = [];
for (i = 0; i < this.length; i++) {
result.push(obj ? fun.bind(obj)(this[i]) : fun(this[i]))
}
return result
}
var arr = [1, 2, 3, 4, 5];
var result = arr.myMap(function (item, index, arr) {
console.log(this)
return item + 1
}, { name: 'zhangsan' })
console.log(result)
九、myFilter
Array.prototype.myFilter = function (fun, obj) {
var result = [];
for (i = 0; i < this.length; i++) {
if (obj ? fun.bind(obj)(this[i]) : fun(this[i])) {
result.push(this[i])
}
}
return result
}
var arr = [1, 2, 3, 4, 5];
var result = arr.myFilter(function (item, index, arr) {
console.log(this)
return item > 2
}, { name: 'zhangsan' })
console.log(result)