TypedArray.prototype.slice()

slice()方法返回一个typed array的部分类型数组对象,数组内容采用浅拷贝方式. 方法采用与 Array.prototype.slice()相同的算法. 类型数组是 typed array types成员中的一员 .

语法

typedarray.slice([begin[, end]])

参数列表

begin:起始位置  可选
从0开始的索引位置;
负值索引, 表示与数组尾元素的偏移量. slice(-2) 表示提取数列中的末尾两个元素.
如果没有设定起始位置,则将从开始位置开始截取。
end:结束位置  可选
从零开始到尾元素前的索引值. slice 取出元素时包含起始节点,单不包含结束节点。
例, slice(1,4) 表示读取第二个元素到第四个元素(元素索引位置:1, 2, and 3).
负值索引, 表示与数组尾元素的偏移量。 slice(2,-1) 表示取出数组中的第三个到最后一个之间的所有元素.
如果没有设定结束位置,则将从开始位置截取到序列尾部。( typedarray.length).

返回值

包含取出元素的新的 typed array

Description

slice方法并不会改变原数组的内容,他只是返回从原数组中取出的元素的浅复制集合。

如何一个新元素被添加到任何一个数组中去,则另外一个数组不会发生变化。

Examples

返回已存在类型数组的部分片段

var 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

Since there is no global object with the name TypedArray, polyfilling must be done on an "as needed" basis.

// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.slice
if (!Uint8Array.prototype.slice) {
  Object.defineProperty(Uint8Array.prototype, 'slice', {
    value: Array.prototype.slice
  });
}

This is not a complete polyfill, since it returns an instance of Array, and not Uint8Array, so it lacks properties that would normally exist on TypedArrays.

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
%TypedArray%.prototype.slice
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
%TypedArray%.prototype.slice
Draft  

Browser compatibility

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
slice Chrome Full support 45 Edge Full support 14 Firefox Full support 38 IE No support No Opera Full support 32 Safari ? WebView Android Full support 45 Chrome Android Full support 45 Firefox Android Full support 38 Opera Android ? Safari iOS ? Samsung Internet Android Full support 5.0 nodejs Full support 4.0.0

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown

See also