Getter/setter on javascript array?

前端 未结 10 2201
闹比i
闹比i 2020-12-01 02:12

Is there a way to get a get/set behaviour on an array? I imagine something like this:

var arr = [\'one\', \'two\', \'three\'];
var _arr = new Array();

for (         


        
10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 02:50

    This answer is just an extension to the solution based on Proxy. See the solution with proxy, in that only get is mentioned but we can also use set as I am showing here.

    Notice: 3rd argument in set can carry the value...

    The code is self explanatory.

    var _arr = ['one', 'two', 'three'];
    
    var accessCount = 0;
    
    function doSomething() {
      accessCount++;
    }
    
    var arr = new Proxy(_arr, {
      get: function(target, name) {
        doSomething();
        return target[name];
      },
      set: function(target, name, val) { doSomething(); target[name] = val; }
    });
    
    function print(value) {
      document.querySelector('pre').textContent += value + '\n';
    }
    
    print(accessCount);      // 0
    print(arr[0]);           // 'one'
    print(accessCount);      // 1
    arr[1] = 10;
    print(accessCount);      // 2
    print(arr[1]);           // 10
    

提交回复
热议问题