TypedArray.prototype.subarray()

TypedArray 实例的 subarray() 方法在同一 ArrayBuffer 存储上返回一个新的类型化数组,并且具有与此类型化数组相同的元素类型。包含开始偏移量,不包含结束偏移量。

¥The subarray() method of TypedArray instances returns a new typed array on the same ArrayBuffer store and with the same element types as for this typed array. The begin offset is inclusive and the end offset is exclusive.

Try it

语法

¥Syntax

js
subarray()
subarray(begin)
subarray(begin, end)

参数

¥Parameters

begin Optional

: 开始的元素。偏移量是包含在内的。如果未指定该值,则整个数组将包含在新视图中。

end Optional

: 结束的元素。偏移量是独占的。如果未指定,则从 begin 指定的元素到数组末尾的所有元素都将包含在新视图中。

返回值

¥Return value

一个新的 TypedArray 对象。

¥A new TypedArray object.

描述

¥Description

beginend 指定的范围被钳位到当前数组的有效索引范围;如果新数组的计算长度为负数,则将其限制为零。如果 beginend 为负数,则它指的是从数组末尾开始的索引,而不是从开头开始的索引。

¥The range specified by begin and end is clamped to the valid index range for the current array; if the computed length of the new array would be negative, it's clamped to zero. If either begin or end is negative, it refers to an index from the end of the array instead of from the beginning.

另请注意,这是在现有缓冲区上创建一个新视图;对新对象内容的更改将影响原始对象,反之亦然。

¥Also note that this is creating a new view on the existing buffer; changes to the new object's contents will impact the original object and vice versa.

示例

¥Examples

使用 subarray() 方法

¥Using the subarray() method

js
const buffer = new ArrayBuffer(8);
const uint8 = new Uint8Array(buffer);
uint8.set([1, 2, 3]);

console.log(uint8); // Uint8Array [ 1, 2, 3, 0, 0, 0, 0, 0 ]

const sub = uint8.subarray(0, 4);

console.log(sub); // Uint8Array [ 1, 2, 3, 0 ]

规范

Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.subarray

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看