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.
typedarray.slice([begin[, end]])
begin
Optional
slice(-2)
extracts the last two elements in the sequence.begin
is undefined, slice
begins from index 0
.end
Optional
slice
extracts up to but not including end
.slice(1,4)
extracts the second element through the fourth element (elements indexed 1, 2, and 3).slice(2,-1)
extracts the third element through the second-to-last element in the sequence.end
is omitted, slice
extracts through the end of the sequence (typedarray.length
).A new typed array containing the extracted elements.
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.
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 ]
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.
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of '%TypedArray%.prototype.slice' in that specification. | Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262) The definition of '%TypedArray%.prototype.slice' in that specification. | Draft |
Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 45 | ? | 38 | No | ? | ? |
Feature | Android webview | Chrome for Android | Edge mobile | Firefox for Android | Opera Android | iOS Safari | Samsung Internet |
---|---|---|---|---|---|---|---|
Basic support | ? | ? | ? | 38 | ? | ? | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice