2020-09-15 00:19:56
在 JavaScript 中,slice() 是数组和字符串共有的方法,用于提取部分内容并返回一个新数组或子字符串,不会修改原数组/字符串。以下是详细使用方法:
一、数组的 slice() 方法语法:arr.slice([start[, end]])参数:
示例:
const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];// 1. 获取前三个元素(索引 0 到 2)const firstThree = fruits.slice(0, 3);console.log(firstThree); // 输出: ['apple', 'banana', 'orange']// 2. 从索引 2 开始到末尾const fromTwo = fruits.slice(2);console.log(fromTwo); // 输出: ['orange', 'grape', 'kiwi']// 3. 使用裤悄负数索引(获取最后两个元素)const lastTwo = fruits.slice(-2);console.log(lastTwo); // 输出: ['grape', 'kiwi']// 4. 提取中间部分(宴伏索引 1 到 3)const middle = fruits.slice(1, 4);console.log(middle); // 输出: ['banana', 'orange', 'grape']二、字符串的 slice() 方法语法:str.slice([start[, end]])参数与数组一致,但返回的是子字符串。
示例:
const message = 'Hello, World!';// 1. 提取前 5 个字符const greeting = message.slice(0, 5);console.log(greeting); // 输出: 'Hello'// 2. 从索引 7 开始到末尾const rest = message.slice(7);console.log(rest); // 输出: 'World!'// 3. 使用负数索引(获取最后 6 个字符)const endPart = message.slice(-6);console.log(endPart); // 输出: 'World!'三、关键特性slice() 不修改原数组,返回子数组。
splice() 会修改原数组,可删除/插入元素。
两者功能类似,但 slice() 支持负数索引,substring() 会将负数视为 0。
通过以上方法,你可以灵活使用 slice() 处理数组和字符串的子集提取需求。