Custom Array-like getter in JavaScript

后端 未结 3 1017
无人及你
无人及你 2021-02-14 05:28

I have a simple ES6 class, like so:

class Ring extends Array {
    insert (item, index) {
        this.splice(index, 0, item);
        return this;
    }
}
         


        
3条回答
  •  爱一瞬间的悲伤
    2021-02-14 06:16

    Basically it is

    class ProxyRing extends Array {
      constructor(...args) {
        super(...args)
    
        return new Proxy(this, {
          get: function (target, name) {
              var len = target.length;
              if (typeof name === 'string' && /^-?\d+$/.test(name))
                  return target[(name % len + len) % len];
              return target[name];
          }
        });
      }
    
      insert (item, index) {
          this.splice(index, 0, item);
          return this;
      }
    }
    

提交回复
热议问题