Array.prototype.slice()

slice() 方法返回一个新的数组对象,这一对象是一个由 startend 决定的原数组的浅拷贝(包括 start,不包括 end),其中 startend 代表了数组元素的索引。原始数组不会被改变。

尝试一下

语法

slice()
slice(start)
slice(start, end)

参数

start 可选

提取起始处的索引(从 0 开始),会转换为整数

  • 如果索引是负数,则从数组末尾开始计算——如果 start < 0,则使用 start + array.length
  • 如果 start < -array.length 或者省略了 start,则使用 0
  • 如果 start >= array.length,则不提取任何元素。
end 可选

提取终止处的索引(从 0 开始),会转换为整数slice() 会提取到但不包括 end 的位置。

  • 如果索引是负数,则从数组末尾开始计算——如果 end < 0,则使用 end + array.length
  • 如果 end < -array.length,则使用 0
  • 如果 end >= array.length 或者省略了 end,则使用 array.length,提取所有元素直到末尾。
  • 如果 end 在规范化后小于或等于 start,则不提取任何元素。

返回值

一个含有被提取元素的新数组。

描述

slice() 方法是一个复制方法。它不会改变 this,而是返回一个浅拷贝,其中包含了原始数组的一部分相同的元素。

slice() 方法会保留空槽。如果被切片的部分是稀疏的,则返回的数组也是稀疏的。

slice() 方法是通用的。它只要求 this 上有 length 属性和整数键属性。

示例

返回现有数组的一部分

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);

// fruits 包含 ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus 包含 ['Orange','Lemon']

使用 slice

在下例中,slicemyCar 创建了一个新数组 newCar。两个数组都包含了一个 myHonda 对象的引用。当 myHondacolor 属性改变为 purple,则两个数组中的对应元素都会随之改变。

// 使用 slice 方法从 myCar 创建一个 newCar。
const myHonda = {
  color: "red",
  wheels: 4,
  engine: { cylinders: 4, size: 2.2 },
};
const myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
const newCar = myCar.slice(0, 2);

console.log("myCar =", myCar);
console.log("newCar =", newCar);
console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);

// 改变 myHonda 对象的 color。
myHonda.color = "purple";
console.log("The new color of my Honda is", myHonda.color);

console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);

上述代码输出:

myCar = [
  { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } },
  2,
  'cherry condition',
  'purchased 1997'
]
newCar = [ { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }, 2 ]
myCar[0].color = red
newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple

在类数组对象上调用 slice()

slice() 方法会读取 this 对象的 length 属性,然后从 startend 读取整数键属性,并将它们定义在一个新创建的数组中。

const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
};
console.log(Array.prototype.slice.call(arrayLike, 1, 3));
// [ 3, 4 ]

使用 slice() 把类数组对象转化为数组

slice() 方法经常与 bind()call() 一起使用,用于创建一个实用方法,将类数组对象转换为数组。

// 调用 slice() 方法时,会将 this 对象作为第一个参数传入
const slice = Function.prototype.call.bind(Array.prototype.slice);

function list() {
  return slice(arguments);
}

const list1 = list(1, 2, 3); // [1, 2, 3]

在稀疏数组上使用 slice()

如果源数组是稀疏数组,slice() 方法返回的数组也会是稀疏数组。

console.log([1, 2, , 4, 5].slice(1, 4)); // [2, empty, 4]

规范

Specification
ECMAScript Language Specification
# sec-array.prototype.slice

浏览器兼容性

BCD tables only load in the browser

参见