我想要扩展Array.push
方法,使得使用push会触发一个回调函数,然后执行正常的数组函数。
我不太确定如何做到这一点,但是这里是我一直在尝试并且没有成功的一些代码。
arr = [];
arr.push = function(data){
//callback method goes here
this = Array.push(data);
return this.length;
}
arr.push('test');
我想要扩展Array.push
方法,使得使用push会触发一个回调函数,然后执行正常的数组函数。
我不太确定如何做到这一点,但是这里是我一直在尝试并且没有成功的一些代码。
arr = [];
arr.push = function(data){
//callback method goes here
this = Array.push(data);
return this.length;
}
arr.push('test');
由于push允许推入多个元素,因此我在下面使用arguments变量来使真正的push方法拥有所有参数。
这个解决方案只影响arr变量:
arr.push = function () {
//Do what you want here...
return Array.prototype.push.apply(this, arguments);
}
这个解决方案会影响所有数组。我不建议你这么做。
Array.prototype.push = (function() {
var original = Array.prototype.push;
return function() {
//Do what you want here.
return original.apply(this, arguments);
};
})();
首先,您需要创建Array
的子类:
ES6 (https://kangax.github.io/compat-table/es6/):
class SortedArray extends Array {
constructor(...args) {
super(...args);
}
push() {
return super.push(arguments);
}
}
ES5(proto 几乎已被弃用,但目前只有它是唯一的解决方案):
function SortedArray() {
var arr = [];
arr.push.apply(arr, arguments);
arr.__proto__ = SortedArray.prototype;
return arr;
}
SortedArray.prototype = Object.create(Array.prototype);
SortedArray.prototype.push = function() {
this.arr.push(arguments);
};
Array.prototype.push在JavaScript 1.2中被引入。它非常简单:
Array.prototype.push = function() {
for( var i = 0, l = arguments.length; i < l; i++ ) this[this.length] = arguments[i];
return this.length;
};
arr = []
arr.push = function(data) {
alert(data); //callback
return Array.prototype.push.call(this, data);
}
如果您处于没有电话的情况下,您也可以选择这个解决方案:
arr.push = function(data) {
alert(data); //callback
//While unlikely, someone may be using "psh" to store something important
//So we save it.
var saved = this.psh;
this.psh = Array.prototype.push;
var ret = this.psh(data);
this.psh = saved;
return ret;
}
还有一种更本地的方法可以实现这个功能: Proxy
const target = [];
const handler = {
set: function(array, index, value) {
// Call callback function here
// The default behavior to store the value
array[index] = value;
// Indicate success
return true;
}
};
const proxyArray = new Proxy(target, handler);
myArray.push = function() {
Array.prototype.push.apply(this, arguments);
myFunction();
return myArray.length;
};
function myFunction() {
for (var i = 0; i < myArray.length; i++) {
//doSomething;
}
}
Array.prototype.push
进行赋值时,你必须非常小心地处理//在此处执行你想要的操作
代码中的内容。如果其中任何内容导致调用Array.push()
(即使是间接的),将会导致JavaScript栈溢出而崩溃。 - Ted Hopp