0
点赞
收藏
分享

微信扫一扫

python可以使用负索引,JavaScript是无法使用负索引

小时候是个乖乖 2022-02-08 阅读 154

python可以使用负索引,JavaScript是无法使用负索引,那么有没有什么办法,可以使得的JavaScript可以使用使用负索引呢?

使用proxy代理器

const arr = [1, 4, 9, 16, 25];
// 如果是数组的话,index就是索引值
const proxy = new Proxy(arr, {
    get: function (target, index) {
        index = Number(index);
        if (index > 0) {
            return target[index];
        } else {
            // 索引为负值,则从尾部元素开始计算索引
            return target[target.length + index];
        }
    }
});
console.log(proxy[2]);  // 9
console.log(proxy[-2]); // 16

举报

相关推荐

0 条评论