javascript 数组从后面取第N个值
侧边栏壁纸
  • 累计撰写 7 篇文章
  • 累计收到 1 条评论

javascript 数组从后面取第N个值

Minpub
2025-11-20 / 0 评论 / 10 阅读 / 正在检测是否收录...


类似Python的arr[-1] // 取最后一位

// 代理数组 可使用 arr[-1] 来获取最后一个元素
Array.prototype.proxy = function(){

return new Proxy(this, {
    get: (t, p, r) => Reflect.get(t, parseInt(p) < 0 ? t.length + parseInt(p) : p, r)
});

}

var a = [1,2,3,4,5,6];
var b = a.proxy();

// 取最后1位
var last1 = b[-1];
console.log(last1); // 6

// 取倒数第4位
var last4 = b[-4];
console.log(last4); // 3

关于js中的Proxy及Reflect,找到相关的说明,正确与否不做辩解,也可自己去查阅相关

js中的Proxy_拾玥花开的博客-CSDN博客_js proxy

js中的Reflect入门讲解_yunchong_zhao的博客-CSDN博客_js reflect

0

评论 (0)

取消