Negative Indexing With Array At
Read array tails with at() negative indexes, get undefined for out-of-range positions, and build ring rotation on top of the same bounds-safe access.
Code
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(','));How the snippet works
Negative Indexing With Array At reduces to the function rotateRight.
Applying it
The primary signature is function rotateRight(items, steps)
The run emits 8 labeled sections — bracket last:, at last:, at second last:, out of range:, empty:, last char:, rotated:, rotated twice: — one per step.
Statements that matter
return items.map((_, i) => items.at(i - shift));
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `rotateRight` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.