← 中文资源

简体中文版本

lastIndexOf 从指定下标向前扫描

lastIndexOf 返回最后一次出现的下标:fromIndex 是向前扫描的起点,负数按 length+fromIndex 折算、越负越直接返回 -1(与 indexOf 把负数钳回 0 不同),找最后一个分隔符是它的典型用法。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

last push: 4
first push: 0
absent: -1
from 2: 2
from -2: 2
from -100: -1
slash at: 10
dir: assets/img

实现说明

演示用的数据放在这几个模块级绑定中:events、path。

使用要点

  • 每一步打印都带着自己的标签:last push:、first push:、absent:。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 状态都挂在模块顶层:events、path。

核心语句

const events = ['push', 'test', 'push', 'lint', 'push'];
const path = 'assets/img/logo.svg';

代码示例

// lastIndexOf scans from the tail toward the head and returns the last matching index
const events = ['push', 'test', 'push', 'lint', 'push'];
console.log('last push:', events.lastIndexOf('push'));
console.log('first push:', events.indexOf('push'));
console.log('absent:', events.lastIndexOf('deploy'));

// the second argument is the position to start scanning from (inclusive)
console.log('from 2:', events.lastIndexOf('push', 2));
console.log('from -2:', events.lastIndexOf('push', -2));

// negatives are normalized as length + fromIndex; still negative after that skips the whole array and returns -1
console.log('from -100:', events.lastIndexOf('push', -100));

// typical use: locate the last path separator
const path = 'assets/img/logo.svg';
console.log('slash at:', path.lastIndexOf('/'));
console.log('dir:', path.slice(0, path.lastIndexOf('/')));