slice()
方法将一个typed array的一部分浅拷贝到一个新的typed array对象中并返回。此方法采用与 Array.prototype.slice()
相同的算法。TypedArray指 typed array types中的一员 .
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
语法
typedarray.slice([begin[, end]])
参数
begin
可选- 从0开始的索引位置。
- 可以使用负值索引, 表示从数组末尾往前的偏移量。
slice(-2)
表示提取数组中的末尾两个元素. - 如果没有设定起始位置,则将从开始位置开始截取。
end
可选- 从0开始到尾元素前的索引值。
slice
取出的元素到此位置之前,不包含该位置。 - 例,
slice(1,4)
表示读取第2个元素到第4个元素(元素索引:1, 2, 3)。 - 可以使用负值索引, 表示从数组末尾往前的偏移量。
slice(2,-1)
表示取出数组中的第3个到倒数第2个元素。 - 如果没有设定结束位置,则将从开始位置截取到序列尾部。(默认值为
typedarray.length
).
返回值
包含取出元素的新 typed array。
描述
slice
方法并不会改变原数组的内容,它只是返回从原数组中取出的元素的浅复制集合。
如果一个新元素被添加到它们任何一个数组中去,另外一个数组不会受到影响。
示例
返回已存在类型数组的一部分片段
const uint8 = new Uint8Array([1,2,3]);
uint8.slice(1); // Uint8Array [ 2, 3 ]
uint8.slice(2); // Uint8Array [ 3 ]
uint8.slice(-2); // Uint8Array [ 2, 3 ]
uint8.slice(0,1); // Uint8Array [ 1 ]
Polyfill
由于没有叫做TypedArray 的全局对象,必须在“按需”的基础上实现 Polyfill。
if (!Uint8Array.prototype.slice) { Object.defineProperty(Uint8Array.prototype, 'slice', { value: function (begin, end) { return new Uint8Array(Array.prototype.slice.call(this, begin, end)); } }); }
这不是一个完整的 polyfill,因为它返回的是一个Array的实例而不是Uint8Array,所以它没有TypedArrays应有的一些属性。
如果你要在不支持 Object.defineProperty
的老旧JavaScript引擎上支持这个特性,最好不要去实现 Array.prototype
中那些方法的 polyfill ,因为你没法让它们不可枚举。
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) %TypedArray%.prototype.slice |
Standard | Initial definition. |
ECMAScript (ECMA-262) %TypedArray%.prototype.slice |
Living Standard |
浏览器兼容性
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.