如何为 JS 数组函数 push、pop、shift 创建自定义函数?
对于推送,我们可以这样做
var arr = [1,2,3];
Array.prototype.push = function(val){
var len = this.length;
this[len] = val;
return arr;
}
arr.push(5);
我们如何做流行音乐?
提前致谢
如何为 JS 数组函数 push、pop、shift 创建自定义函数?
对于推送,我们可以这样做
var arr = [1,2,3];
Array.prototype.push = function(val){
var len = this.length;
this[len] = val;
return arr;
}
arr.push(5);
我们如何做流行音乐?
提前致谢
好吧,您可以通过更改其原型来更改所有数组的 push 函数的行为:
js> Array.prototype.push = function() { print('\\_o< quack!'); }
(function () {print("\\_o< quack!");})
js> [].push(1)
\_o< quack!
或者您可以为给定实例更改它:
js> a = []
[]
js> a.push = function() { print('\\_o< quack!'); }
(function () {print("\\_o< quack!");})
js> b = []
[]
js> a.push(1)
\_o< quack!
js> b.push(1)
1
js> print(b);
1
同样的事情适用于其他方法。
要实现您自己的 pop() 方法,一般算法将是:
js> Array.prototype.pop = function() { var ret = this[this.length-1]; this.splice(this.length, 1); return ret }
但是使用 splice(),实际上可以使它更简单:
js> Array.prototype.pop = function() { return this.splice(this.length-1, 1)[0]; }
移位可以采用相同的方法:
js> Array.prototype.shift = function() { var ret = this[0]; this.splice(0, 1); return ret }
js> Array.prototype.shift = function() { return this.splice(0, 1)[0]; }
var Mainarray=new Array();
var index=0;
function Push(value){
Mainarray[index++]=value;
}
function Pop(){
if(index>0){
index--;
return Mainarray[index];
}
else{
// display message of Empty Array
}
}