实现数组下标为-1访问最后一个元素

92 阅读1分钟

当时只回答了大致思路,proxy 这些,具体咋实现没答出来。今天早上突然想到这个问题,以为面试官要考我原型链继承

      function Father() {
        this.numbers = ["1", "2", "3", "4"];
      }
      function Son() {
        Father.call(this);
      }
      Son.prototype = new Father()
      const son = new Son();

Son.prototype 我回答成了直接指向 Father.prototype 被追问了

肯定是要实现一个伪数组的,为了避免 push 这些已有的方法再实现一遍,我才想到了继承,可这样-1 只能被当做函数调用。

Object.defineProperties

    function GrowArr() {
      const arr = [...arguments];
      Object.defineProperties(arr, {
        "-1": {
          get() {
            //防止空数组造成死循环
            return arr.length > 0 ? arr[arr.length - 1] : undefined;
          },
        },
      });

      return arr;
    }
    const arr = new GrowArr();
    console.log(arr[-1]);

const arr = [...arguments]; 此处如果是 const arr = new Array(...arguments);,当初始化长度为 1 时就会变成定义数组长度

Proxy

既然-1 可以访问数组的最后一个元素,那么-2 也应该访问倒数第二个才合理些

    function GrowArr() {
      const arrProxy = new Proxy([...arguments], {
        get: function (target, property) {
          if (property >= 0) {
            return target[property];
          }
          return target[target.length + +property];
        },
      });

      return arrProxy;
    }

    const arr = new GrowArr(1, 2);

    console.log(arr[-1]);