33

我正在尝试扩展该Array.push方法,以便使用 push 将触发回调方法,然后执行正常的数组函数。

我不太确定如何做到这一点,但这里有一些我一直没有成功的代码。

arr = [];
arr.push = function(data){

    //callback method goes here

    this = Array.push(data);
    return this.length;
}

arr.push('test');
4

6 回答 6

75

由于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);
    };
})();
于 2009-02-21T08:24:50.117 回答
11

首先你需要子类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);
};
于 2016-10-10T19:20:40.110 回答
6

你可以这样做:

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;
}

虽然我在告诉您如何操作,但您最好使用执行回调的不同方法,然后只在数组上调用push而不是覆盖push。您最终可能会遇到一些意想不到的副作用。例如,push似乎是可变的(采用可变数量的参数,如printf),使用上述内容会破坏它。

您需要弄乱 _Arguments() 和 _ArgumentsLength() 才能正确覆盖此函数。我强烈反对这条路线。

或者您可以使用“参数”,这也可以。我仍然建议不要走这条路。

于 2009-02-21T08:20:18.193 回答
6

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;
};

你总是可以在前面添加一些东西。

于 2009-04-02T23:22:50.290 回答
1

还有另一种更原生的方法来实现这一点: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);
于 2020-05-29T08:34:47.273 回答
0

我想在对象被推送到数组后调用一个函数,所以我做了以下事情:

myArray.push = function() { 
    Array.prototype.push.apply(this, arguments);
    myFunction();
    return myArray.length;
};

function myFunction() {
    for (var i = 0; i < myArray.length; i++) {
        //doSomething;
    }
}
于 2015-02-21T15:38:12.090 回答