javascript - 在 Javascript 数组上生成事件

标签 javascript arrays dom-events custom-events

当 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/

相关文章:

javascript - 如果我不测试被动事件监听器支持会发生什么?

javascript - 如何让服务器与客户端对话

javascript - 单击转到 url 和内容类名更改

javascript - 如何在javascript中显示div表单列表

c++ - 具有 POD 和未初始化值数组的 auto_ptr

php - 使用 array_flip 函数后同一键缺少值

javascript - 卸载以使用跨浏览器的按钮

javascript - 多条件语句 JavaScript

java - java中基于其他数组对数组进行排序

javascript - 未捕获的类型错误 : Cannot read property 'addEventListener' of undefined at app. js:4