Skip to content

第 30 题:使用ES6 的Proxy实现数组负索引。 (负索引:例如,可以简单地使用arr[-1]替代arr[arr.length-1]访问最后一个元素,[-2]访问倒数第二个元素,以此类推) #36

@lgwebdream

Description

@lgwebdream
Owner

欢迎在下方发表您的优质见解


每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案
欢迎大家在下方发表自己的优质见解
二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

Activity

changed the title [-]第 30 题:手写用 ES6proxy 如何实现 arr[-1] 的访问[/-] [+]第 30 题:使用ES6 的Proxy实现数组负索引。 (负索引:例如,可以简单地使用arr[-1]替代arr[arr.length-1]访问最后一个元素,[-2]访问倒数第二个元素,以此类推)[/+] on Jun 20, 2020
Genzhen

Genzhen commented on Jun 23, 2020

@Genzhen
Collaborator
const negativeArray = els =>
    new Proxy(els, {
        get: (target, propKey, receiver) =>
            Reflect.get(
                target,
                +propKey < 0 ? String(target.length + +propKey) : propKey,
                receiver
            )
    });
const unicorn = negativeArray(["京", "程", "一", "灯"]);
unicorn[-1]; 
yaooooooooo

yaooooooooo commented on Jul 20, 2020

@yaooooooooo

楼上的成倍数索引有问题。

MADAO-art

MADAO-art commented on Aug 2, 2020

@MADAO-art
    "use strict";
    let arr=[1,2,4,6,8,10];
    function Arrchange(arr){
        let proxy=new Proxy(arr,{
            set(){},
            get(arr,property){          
                if(property>=0){
                    return arr[property]
                }else{
                    return arr[(arr.length+property*1)]
                }
            }
        }); 
        return proxy; 
    }  
    let brr=new Arrchange(arr);
    console.log(brr[0]);
xiaotianxia

xiaotianxia commented on Aug 8, 2020

@xiaotianxia
const proxyArray = arr => {
    const length = arr.length;
    return new Proxy(arr, {
        get(target, key) {
            key = +key;
            while (key < 0) {
                key += length;
            }
            return target[key];
        }
    })
};
var a = proxyArray([1, 2, 3, 4, 5, 6, 7, 8, 9]);
console.log(a[1]);  // 2
console.log(a[-10]);  // 9
console.log(a[-20]);  // 8
yh27tc

yh27tc commented on Aug 18, 2020

@yh27tc
function ArrProxy(arr) {
    return new Proxy(arr, {
        get(arr, index) {
            // 模拟机器取模运算
            const modIndex = index % arr.length;
            return arr[modIndex < 0 ? arr.length + modIndex : modIndex];
        },
        set(){}
    })
}
zojize

zojize commented on Oct 19, 2020

@zojize
// 30.手写用 ES6proxy 如何实现 arr[-1] 的访问
function PythonArray(arr) {
  return new Proxy(arr, {
    get(target, prop, receiver) {
      if ((key = Number.parseInt(prop))) {
        const len = Reflect.get(target, 'length', receiver);
        prop = key < 0 && Math.abs(key) <= len ? len + key : prop;
      }
      return Reflect.get(target, prop, receiver);
    },
    set(target, prop, value, receiver) {
      if ((key = Number.parseInt(prop))) {
        const len = Reflect.get(target, 'length', receiver);
        prop = key < 0 && Math.abs(key) <= len ? len + key : prop;
      }
      return Reflect.set(target, prop, value, receiver);
    },
    deleteProperty(target, prop) {
      if ((key = Number.parseInt(prop))) {
        const len = target.length;
        prop = key < 0 && Math.abs(key) <= len ? len + key : prop;
      }
      return Reflect.deleteProperty(target, prop);
    },
  });
}
zengxiaoluan

zengxiaoluan commented on Mar 30, 2021

@zengxiaoluan
var arr = [1,2,[3,[4,[5]]]]

function proxyArr(arr) {
    for(let i = 0; i < arr.length; i++) {
        let item = arr[i];
        if(Array.isArray(item)) arr[i] = proxyArr(item)
    }
    return new Proxy(arr,{
        get(arr, index, proxiedArr){
            let len = arr.length
            index = +index
            index = index < 0 ? index + len : index
            return arr[index]
        }
    })
}

var proxied = proxyArr(arr)

console.log(proxied[-1][-1][-1][-1])
Luoyuda

Luoyuda commented on Jun 10, 2021

@Luoyuda
    function proxyArray(arr){
        return new Proxy(arr, {
            get(target, key){
                if(key >= 0) return target[key]
                let len = target.length
                return target[len + (key % len)]
            }
        })
    }
    var arr = proxyArray([1, 2, 3, 4, 5, 6, 7, 8, 9]);
    console.log(arr[0], arr[1])
    console.log(arr[-10], arr[-20])
geekftz

geekftz commented on Jul 21, 2021

@geekftz

const newArrayProducer = (arr) =>
new Proxy(arr, {
get: function (obj, prop) {
console.log('%c prop = %s', 'color: #408059', prop);

  prop = prop >= 0 ? prop : arr.length - Math.abs(prop);

  return obj[prop];
},

});

var newArr = newArrayProducer([1, 2, 3]);

1uckyneo

1uckyneo commented on Sep 30, 2021

@1uckyneo
const genNegativeIndexAccessibleArray = <T>(arr: T[]) => {
  return new Proxy(arr, {
    get(target, key) {
      if (typeof key !== 'symbol') {
        const index = Number.parseInt(key, 10);

        if (index < 0) {
          const computedIndex = target.length + index;
          return Reflect.get(target, computedIndex);
        }
      }

      return Reflect.get(target, key);
    },
  });
};

const a = genNegativeIndexAccessibleArray([
  1, 2, 3, 4, 5, 6, 7, 8, 9,
]);

console.log(a[1]); // 2
console.log(a[-1]); // 9
console.log(a[-2]); // 8
zizxzy

zizxzy commented on Nov 3, 2021

@zizxzy

proxy的介绍proxy
利用proxy重写[]

const negativeIndex = arr => {
  return new Proxy(arr, {
    get: (target, proKey) => {
      let index = Number(proKey);
      let length = target.length;
      while (index < 0) {
        index += length;
      }
      return target[index];
    }
  })
}

console.log(negativeIndex([1, 2, 3, 4, 5, 6, 7])[-1]);
console.log(negativeIndex([1, 2, 3, 4, 5, 6, 7])[-20]);
LiquidLiquids

LiquidLiquids commented on Dec 23, 2021

@LiquidLiquids

不判断数字索引,length push访问是有问题的。

lang711

lang711 commented on Aug 27, 2022

@lang711
    const proxyArr = arr => new Proxy(arr, {
      get(target, key, proxy) {
        let index = (target.length + +key) % target.length;
        return target[+index];
      },
      set(target, key, value, proxy) {
        
      },
    });
    // 测试
    const arr = [2, 34, 65, 7, 4, 56, 78, 5, 2, 8, 0, 5, 98, 435];
    console.log(proxyArr(arr)[-1]);
chinbor

chinbor commented on Aug 7, 2023

@chinbor
const negativeArr = (ele) => {
  return new Proxy(ele, {
    get(target, key, receiver) {
      if (Array.isArray(ele)) {
        const len = target.length
        const intKey = Number(key)

        return Reflect.get(target, intKey < 0 ? len + intKey : intKey, receiver)
      }

      return Reflect.get(target, key, receiver)
    }
  })
}

const test = negativeArr([1, 2, 3, 4, 5])
console.log(test[-1])
console.log(test[-2])

const obj = negativeArr({'-1': 1, '-2': 2})
console.log(obj[-1])
console.log(obj[-2])
Kisthanny

Kisthanny commented on Mar 21, 2024

@Kisthanny
/**
 * 手写用 ES6proxy 如何实现 arr[-1] 的访问
 */

const originArr = [1, 2, 3, 4, 5];
const arrProxy = new Proxy(originArr, {
  get: function (target, property, receiver) {
    const rawIndex = Number(property)
    const finalIndex = rawIndex < 0 ? target.length + rawIndex : rawIndex;
    console.log(`reading index ${finalIndex}`);
    return Reflect.get(target, finalIndex, receiver);
  },
});

console.log(arrProxy[0]);
console.log(arrProxy[1]);
console.log(arrProxy[2]);
console.log(arrProxy[3]);
console.log(arrProxy[4]);
console.log(arrProxy[-1]);
console.log(arrProxy[-2]);
console.log(arrProxy[-3]);
console.log(arrProxy[-4]);
console.log(arrProxy[-5]);
lzdml

lzdml commented on Apr 14, 2024

@lzdml
/**
* arr[-1] === arr[arr.length + (-1)]
* arr[-2] === arr[arr.length + (-2)]
*
* arr[-n] === arr[arr.length + (-n)]
**/

const arr = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 3, name: "Charlie" },
  { id: 4, name: "David" },
  { id: 5, name: "Eve" },
  { id: 6, name: "Frank" },
];

function proxyArray(arr) {
  const len = arr.length;
  return new Proxy(arr, {
    get(target, key) {
      return target[len + key * 1];
    },
  });
}

const a = proxyArray(arr);
console.log("a[-1] :>> ", a[-1]);
console.log("a[-2] :>> ", a[-2]);
console.log("a[-6] :>> ", a[-6]);
console.log("a[-7] :>> ", a[-7]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @yh27tc@lgwebdream@xiaotianxia@zengxiaoluan@Luoyuda

        Issue actions

          第 30 题:使用ES6 的Proxy实现数组负索引。 (负索引:例如,可以简单地使用arr[-1]替代arr[arr.length-1]访问最后一个元素,[-2]访问倒数第二个元素,以此类推) · Issue #36 · lgwebdream/FE-Interview