The slice() method returns a shallow copy of a portion of a typed array into a new typed array object. This method has the same algorithm as Array.prototype.slice(). TypedArray is one of the typed array types here.
Syntax
typedarray.slice([begin[, end]])
Parameters
beginOptional- Zero-based index at which to begin extraction.
- As a negative index,
beginindicates an offset from the end of the sequence.slice(-2)extracts the last two elements in the sequence. - If
beginis omitted,slicebegins from index0. endOptional- Zero-based index at which to end extraction.
sliceextracts up to but not includingend. slice(1,4)extracts the second element up to the fourth element (elements indexed 1, 2, and 3).- As a negative index,
endindicates an offset from the end of the sequence.slice(2,-1)extracts the third element through the second-to-last element in the sequence. - If
endis omitted,sliceextracts to the end of the sequence (arr.length).
Return value
A new typed array containing the extracted elements.
Description
The slice method does not alter. It returns a shallow copy of elements from the original typed array.
If a new element is added to either typed array, the other typed array is not affected.
Examples
Return a portion of an existing typed array
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 ]
Specifications
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of '%TypedArray%.prototype.slice' in that specification. |
Standard | Initial definition. |
| ECMAScript 2017 Draft (ECMA-262) The definition of '%TypedArray%.prototype.slice' in that specification. |
Draft |
Browser compatibility
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 45 | 38 (38) | No support | No support | No support |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | No support | No support | 38 (38) | No support | No support | No support |