当 Javascript 数组的内容被修改时,如何生成事件,即在该特定 Javascript 数组上执行推送或弹出操作时应生成事件。基本上,我想跟踪对特定 Javascript 数组执行的推送、弹出操作。
编辑:- 注释中所述的解决方案需要重写push 或pop 方法。我想执行它而不覆盖它。
最佳答案
这个想法是数组是对象,因此您可以定义属性。
var someArray = []; // a normal array
someArray.push = function() { // this will override the original push method
// custom code here
console.log('pushing something..');
return Array.prototype.push.apply(this, arguments); // original push
};
// now everytime you push something a message will be logged. Change this functionality as you like.
注意:someArray.push() 现在将是可枚举的。如果您想防止这种情况发生,您可以使用 Object.property 方法定义“push”属性。
Object.defineProperty(someArray, 'push', {
enumerable: false, // it's false by default anyway
value: function() {
console.log('pushing something..');
return Array.prototype.push.apply(this, arguments);
}
});
关于javascript - 在 Javascript 数组上生成事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31741081/