lastIndexOf fromIndex Is the Scan Start

Search arrays from the right with lastIndexOf, whose fromIndex marks where the backward scan begins and silently clamps out-of-range starts instead of throwing.

JavascriptData Integrity

Code

javascriptsnippet
17 lines
const events = ["push", "merge", "push", "revert", "push"];

console.log(events.lastIndexOf("push"));        // 从右向左:4
console.log(events.indexOf("push"));            // 从左向右:0

// fromIndex 是“从此处开始向左扫”,所以起始位本身也算
console.log(events.lastIndexOf("push", 3));     // 2

// fromIndex >= length 时按 length-1 处理;负数加 length
console.log(events.lastIndexOf("push", 99));    // 4
console.log(events.lastIndexOf("push", -2));    // 2:等价 fromIndex 3

// lastIndexOf 用严格相等,NaN 永远找不到
console.log([NaN].lastIndexOf(NaN), [NaN].indexOf(NaN));

// 对象是引用比较:两次字面量不相等
console.log([{ id: 1 }].lastIndexOf({ id: 1 }));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

4
0
2
4
2
-1 -1
-1

How it works

Demo state sits in top-level bindings: events.

events.lastIndexOf("push") scans right-to-left over ["push", "merge", "push", "revert", "push"] and returns 4, while indexOf returns the leftmost 0. With fromIndex the scan starts there and includes it: lastIndexOf("push", 3) finds index 2, lastIndexOf("push", 99) clamps to length-1 (4), and -2 resolves to length-2 = 3 before scanning.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.

Key statements

const events = ["push", "merge", "push", "revert", "push"];

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `events`.