← 中文资源

简体中文版本

用 Array.prototype.at 负索引取值

用 at() 的负索引读取数组尾部,越界统一返回 undefined 不抛错,字符串同样支持;环形右移这类场景直接建立在负索引访问之上。

阅读英文原文

实现说明

用 Array.prototype.at 负索引取值的核心是函数 rotateRight。

使用要点

  • 直接运行文件,输出会带上标签,比如 bracket last:、at last:、at second last:——输出的每一行都能指回产生它的那次调用。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 rotateRight。

签名一览:function rotateRight(items, steps)

核心语句

return items.map((_, i) => items.at(i - shift));

代码示例

const stages = ['build', 'test', 'deploy'];

// 旧写法:先做长度算术,容易 off-by-one
console.log('bracket last:', stages[stages.length - 1]);

// at() 直接支持负索引(negative index)
console.log('at last:', stages.at(-1));
console.log('at second last:', stages.at(-2));

// 越界统一返回 undefined,不抛错
console.log('out of range:', stages.at(99), stages[99]);

// 空数组同样安全
console.log('empty:', [].at(-1));

// 字符串同样支持 at()
console.log('last char:', 'deploy'.at(-1));

// Array.prototype.at 的实用场景:环形右移
function rotateRight(items, steps) {
  const shift = steps % items.length;
  return items.map((_, i) => items.at(i - shift));
}
console.log('rotated:', rotateRight(stages, 1).join(','));
console.log('rotated twice:', rotateRight(stages, 8).join(','));