Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写用 ES6proxy 如何实现 arr[-1] 的访问(滴滴2020) #134

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 comments
Open

Comments

@Sunny-117
Copy link
Owner

No description provided.

@CXGBro
Copy link

CXGBro commented Dec 24, 2022

let arr= [1,2,3,4]
let proxy = new Proxy(arr,{
  get(target,key){
    if(key<0){
      return target[target.length+parseInt(key)]
    }
    return target[key] 
  }
})
console.log(proxy[-2]);
console.log(proxy[2]);

@cscty
Copy link

cscty commented Jul 4, 2023

        let a = [1, 2, 3];
        let proxy = new Proxy(a, {
            get(target, key) {
                if (key === "-1") {
                    return target[target.length - 1];
                }
            },
        });
        console.log(proxy[-1]);

@mafeiGitHub
Copy link

let arr = [1, 2, 3, 4]
let proxy = new Proxy(arr, {
    get(target, key) {
        if (key < 0) {
            return target[target.length + parseInt(key)]
        }
        return target[key]
    }
})
// 测试
console.log(proxy[-1]);

@dizao006
Copy link

dizao006 commented Oct 6, 2024

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function observe(arr) {
  const proxy = new Proxy(arr, {
    get(target, key) {
      let v = target[key];
      if (typeof v === "object") {
        observe(v);
      }
      if (key < 0) {
        let len = target.length;
        key = len - -key;
      }
      return target[key];
    },
  });
  return proxy;
}

const arr2 = observe(arr);
console.log(arr2[-4]);

@Windseek
Copy link

const arrProxy = (arr, index) => {
  let proxy = new Proxy(arr, {
    get: (target, key) => {
      if(key < 0) {
        return target[target.length - key*-1];
      }
      return target[key];
    }
  })

  return proxy[index];
}

var a = [1, 2, 3, 4, 5];
console.log(arrProxy(a, -1));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants