假如我想让数组支持负数索引,实现如下效果
let a = [1,2,3]; console.log(a[-1]); // 3
提示:这样做可能会有问题,例如和其他程序员写的模块冲突,但是我们现在不管这个事情,就是想知道能不能实现。
我目前写了段如下的代码
const pyArray = function(a){ return new Proxy(a, { get: function(target, prop, receiver) { let index = Number(prop); if (index < 0) { prop = String(target.length + index); }; return Reflect.get(target, prop, receiver); } }); }; let a = [1, 2, 3]; let b = pyArray(a) console.log(b[-1]); // 3 console.log(a[-1]); // undefined
这里虽然用 Proxy 实现了类似的效果,但是并没有改变原生数组的行为。
能不能改写原生数组的行为,让 a[-1]也能返回 3 ?
1 optional 2019-10-03 17:52:23 +08:00 ![]() 不行 |
![]() | 2 jamesliu96 2019-10-03 18:07:14 +08:00 via Android 应该只能用 Proxy |
![]() | 3 airyland 2019-10-03 18:09:09 +08:00 原生数组的行为是不能变化了,只能对封装对象有效。不过这样的话和直接写工具函数没什么区别了,还不用考虑兼容问题。 https://github.com/sindresorhus/negative-array |
![]() | 4 love 2019-10-03 20:45:40 +08:00 别在内置对象上加功能是共识。 另外你这个改变也有不兼容风险,毕竟如果有库依赖-1 得到 undefined 的行为呢 |
![]() | 5 xuanbg 2019-10-03 21:01:40 +08:00 这样的需求意义何在? |