javascript instance method
ArrayBuffer.prototype.slice()
The slice() method of ArrayBuffer instances returns a new ArrayBuffer whose contents are a copy of this ArrayBuffer’s bytes from start, inclusive, up to end, exclusive. If either start or end is negative, it refers to an index from the end of the array, as opposed to from the beginning.
Interactive exampleOpen the canonical MDN source to run this embedded demo.
// Create an ArrayBuffer with a size in bytes
const buffer = new ArrayBuffer(16);
const int32View = new Int32Array(buffer);
// Produces Int32Array [0, 0, 0, 0]
int32View[1] = 42;
const sliced = new Int32Array(buffer.slice(4, 12));
// Produces Int32Array [42, 0]
console.log(sliced[0]);
// Expected output: 42
Syntax
slice()
slice(start)
slice(start, end)
Parameters
startOptional- : Zero-based index at which to start extraction, converted to an integer.
- Negative index counts back from the end of the buffer — if
-buffer.length <= start < 0,start + buffer.lengthis used. - If
start < -buffer.lengthorstartis omitted,0is used. - If
start >= buffer.length, an empty buffer is returned.
- Negative index counts back from the end of the buffer — if
- : Zero-based index at which to start extraction, converted to an integer.
endOptional- : Zero-based index at which to end extraction, converted to an integer.
slice()extracts up to but not includingend.- Negative index counts back from the end of the buffer — if
-buffer.length <= end < 0,end + buffer.lengthis used. - If
end < -buffer.length,0is used. - If
end >= buffer.lengthorendis omitted isundefined,buffer.lengthis used, causing all elements until the end to be extracted. - If
endimplies a position before or at the position thatstartimplies, an empty buffer is returned.
- Negative index counts back from the end of the buffer — if
- : Zero-based index at which to end extraction, converted to an integer.
Return value
A new ArrayBuffer containing the extracted elements. It is not resizable, even if the original was.
Examples
Copying an ArrayBuffer
const buf1 = new ArrayBuffer(8);
const buf2 = buf1.slice(0);
Specifications
SpecificationsStandards references are available on the canonical MDN page.
Browser compatibility
Browser compatibilityCompatibility data is available on the canonical MDN page.