1. slice()
slice(start, end):
字符串和数组都可以使用slice方法。slice 方法用于从字符串或数组中提取指定范围的子串或子数组,并返回一个新的字符串或数组。并不会改变原字符串和数组。
它接受两个参数,start 表示起始位置(包含),end 表示结束位置(不包含)。如果省略 end 参数,则提取从 start 位置到字符串或数组末尾的所有元素。
const str = 'Hello, World!'
console.log(str.slice(7, 12)) // "World"
const arr = [1, 2, 3, 4, 5]
console.log(arr.slice(2, 4)) // [3, 4]
console.log(str.slice(1)) // ello, World!
console.log(arr.slice(1)) // [2, 3, 4, 5]
// 如果start是负数,则会从数组尾部开始算起。这里只有start没有end,且start为负数,所以只能获取到最后1个元素
console.log(str.slice(-1)) // !
console.log(arr.slice(-1)) // [ 5 ]
console.log(str.slice(1, -1)) // ello, World
console.log(arr.slice(1, -1)) // [ 2, 3, 4 ]
// 获取除了最后1个元素以外的全部元素
console.log(str.slice(0, -1)) // Hello, World
console.log(arr.slice(0, -1)) // [ 1, 2, 3, 4 ]
// 都为负数,值为空字符创或空数组
console.log(str.slice(-1, -1)) // ""
console.log(arr.slice(-1, -1)) // []
2. splice ()
splice(start, deleteCount, item1, item2, ...):
splice 方法用于修改原始数组,可以删除、替换或插入元素,并返回被删除的元素组成的数组。它接受多个参数,其中 start 表示起始位置,deleteCount 表示要删除的元素个数,item1, item2, ... 表示要插入的新元素。
splice 方法不可以用于字符串
const arr1 = [1, 2, 3, 4, 5]
console.log(arr1.splice(2, 2, 6, 7)) // 从数组下标2的位置,删除2个元素,并添加6和7两个值
// [ 3, 4 ] splice方法的返回值是被删除的元素组成的数组。
console.log(arr1) // arr1 变为 [1, 2, 6, 7, 5]
const arr2 = [1, 2, 3, 4, 5]
console.log(arr2.splice(2, 0, 6)) // [] 从数组下标2的位置,删除0个元素,并添加6
console.log(arr2) // arr2 变为 [ 1, 2, 6, 3, 4, 5 ]
const arr3 = [1, 2, 3, 4, 5]
console.log(arr3.splice(-1, 1, 6)) // [ 5 ] 返回了数组的最后一位,并添加6
console.log(arr3) // arr3 变为 [ 1, 2, 3, 4, 6 ]
const arr4 = [1, 2, 3, 4, 5]
console.log(arr4.splice(-1, 0, 6)) // [] 从最后1个元素开始且不删除元素,同时在最后1个元素前面新增1个元素
console.log(arr4) // arr4 变为 [ 1, 2, 3, 4, 6, 5 ]
const arr5 = [1, 2, 3, 4, 5]
console.log(arr5.splice(-1, 3)) // [ 5 ] 截取到数组的最后一个元素后会停止
console.log(arr5) // arr5 变为 [ 1, 2, 3, 4 ]
const arr6 = [1, 2, 3, 4, 5]
console.log(arr6.splice(-1, 2)) // [ 5 ] // 当start为-1时,不管end的值是多少,都表示截取到数组的最后一个元素后会停止
console.log(arr6) // arr6 变为 [ 1, 2, 3, 4 ]
3. substring()
substring(start, end):
substring 方法用于从字符串中提取指定范围的子串,并返回一个新的字符串。
它接受两个参数,start 表示起始位置(包含),end 表示结束位置(不包含)。
如果省略 end 参数,则提取从 start 位置到字符串末尾的所有字符。
const str = 'Hello, World!';
console.log(str.substring(7, 12)); // World
console.log(str.substring(1)); // ello, World!
console.log(str.substring(0)); // Hello, World!
console.log(str.substring(-1)); // Hello, World!
console.log(str.substring(2, -2)); // He
4. substr()
substr(start, length):
substr 方法用于从字符串中提取指定长度的子串,并返回一个新的字符串。
它接受两个参数,start 表示起始位置(包含),length 表示要提取的字符个数。
如果省略 length 参数,则提取从 start 位置到字符串末尾的所有字符。
const str = 'Hello, World!';
console.log(str.substr(7, 1)); // W
console.log(str.substr(7, 2)); // Wo
console.log(str.substr(1)); // ello, World!
console.log(str.substr(0)); // Hello, World!
console.log(str.substr(-1)); // !
console.log(str.substr(-3)); // ld!
console.log(str.substr(2, -2)); // '' length 不管传0,-1,-2等都返回空字符串
如果帮助到您了,可以留下一个赞👍告诉我