TypedArray 实例的 subarray() 返回一个新的、基于相同 ArrayBuffer、元素类型也相同的类型化数组。开始的索引将会被包括,而结束的索引将不会被包括。
{{InteractiveExample("JavaScript Demo: TypedArray.subarray()")}}
```js interactive-example const uint8 = new Uint8Array([10, 20, 30, 40, 50]);
console.log(uint8.subarray(1, 3)); // Expected output: Uint8Array [20, 30]
console.log(uint8.subarray(1)); // Expected output: Uint8Array [20, 30, 40, 50]
## 语法
```js-nolint
subarray()
subarray(begin)
subarray(begin, end)
参数
- begin {{optional_inline}}
- : 元素开始的索引,开始索引的元素将会被包括。若该值没有传入,将会返回一个拥有全部元素的数组。
- end {{optional_inline}}
- : 元素结束的索引,结束索引的元素将不会被包括。若该值没有传入,从
begin所指定的那一个元素到数组末尾的所有元素都将会被包含进新数组中。
- : 元素结束的索引,结束索引的元素将不会被包括。若该值没有传入,从
返回值
一个新的 TypedArray 对象。
说明
- 被
begin和end指定的范围将会收束与当前数组的有效索引 - 若计算后得出的长度是负数,将会被收束成 0
- 若
begin或end是负数,将会被当做成是从数组末端读取的索引
需要注意的是,使用该方法返回的新数组还是建立在原有的 Buffer 之上的,所以,改动数组的内容将会影响到原数组,反之亦然。
Examples
Using the subarray method
var buffer = new ArrayBuffer(8);
var uint8 = new Uint8Array(buffer);
uint8.set([1, 2, 3]);
console.log(uint8); // Uint8Array [ 1, 2, 3, 0, 0, 0, 0, 0 ]
var sub = uint8.subarray(0, 4);
console.log(sub); // Uint8Array [ 1, 2, 3, 0 ]
Specifications
Browser compatibility
See also
- JavaScript typed arrays
TypedArrayArrayBuffer