Array.prototype.toSpliced()
Array
实例的 toSpliced()
方法是
方法的复制版本。它会返回一个新数组,其中在给定索引处移除了和/或替换了某些元素。splice()
语法
toSpliced(start)
toSpliced(start, skipCount)
toSpliced(start, skipCount, item1)
toSpliced(start, skipCount, item1, item2)
toSpliced(start, skipCount, item1, item2, /* …, */ itemN)
参数
start
-
从数组开始更改的零基索引,转换为整数。
- 负数索引从数组末尾开始计数——如果
-array.length <= start < 0
,则使用start + array.length
。 - 如果
start < -array.length
或省略了start
,则使用0
。 - 如果
start >= array.length
,则不会删除任何元素,但该方法会像添加函数一样,添加提供的所有元素。
- 负数索引从数组末尾开始计数——如果
skipCount
可选-
一个整数,表示从
start
开始要从数组中删除(或跳过)的元素数量。如果省略
skipCount
,或者其值大于或等于start
指定位置之后的元素数量,则将删除从start
到数组末尾的所有元素。但是,如果你想传递任何itemN
参数,你应该将Infinity
作为skipCount
来传递,以删除start
之后的所有元素,因为显式的undefined
会被转换为0
。如果
skipCount
是0
或负数,则不会删除任何元素。在这种情况下,你应该指定至少一个新元素(见下文)。 item1
, …,itemN
可选-
要添加到数组的元素,从
start
开始。如果你没有指定任何元素,
toSpliced()
将只从数组中删除元素。
返回值
一个新数组,由 start
之前的所有元素、item1
、item2
、……、itemN
以及 start + skipCount
之后的所有元素组成。
描述
toSpliced()
方法与 splice()
一样,可以一次完成多项操作:它从数组中移除指定数量的元素,从指定的索引开始,然后在同一索引处插入指定的元素。但是,它返回的是一个新数组,而不是修改原始数组。因此,被删除的元素不会从此方法返回,但它们仍然可以在原始数组中访问。
toSpliced()
方法从不生成稀疏数组。如果源数组是稀疏的,空槽将在新数组中被 undefined
替换。
toSpliced()
方法是通用的。它只期望 this
值具有 length
属性和整数键属性。
示例
删除、添加和替换元素
你可以使用 toSpliced()
来删除、添加和替换数组中的元素,并创建一个比使用 slice()
和 concat()
更高效的新数组。
const months = ["Jan", "Mar", "Apr", "May"];
// Inserting an element at index 1
const months2 = months.toSpliced(1, 0, "Feb");
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]
// Deleting two elements starting from index 2
const months3 = months2.toSpliced(2, 2);
console.log(months3); // ["Jan", "Feb", "May"]
// Replacing one element at index 1 with two new elements
const months4 = months3.toSpliced(1, 1, "Feb", "Mar");
console.log(months4); // ["Jan", "Feb", "Mar", "May"]
// Original array is not modified
console.log(months); // ["Jan", "Mar", "Apr", "May"]
在稀疏数组上使用 toSpliced()
toSpliced()
方法总是创建一个密集数组。
const arr = [1, , 3, 4, , 6];
console.log(arr.toSpliced(1, 2)); // [1, 4, undefined, 6]
在非数组对象上调用 toSpliced()
toSpliced()
方法读取 this
的 length
属性。然后它读取所需的整数键属性,并将它们写入新数组。
const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
};
console.log(Array.prototype.toSpliced.call(arrayLike, 0, 1, 2, 3));
// [2, 3, undefined, 4]
规范
规范 |
---|
ECMAScript® 2026 语言规范 # sec-array.prototype.tospliced |
浏览器兼容性
加载中…