TypedArray.prototype.fill()
fill()方法将类型化数组中的从起始索引到终止索引内的全部元素。这个方法的算法和Array.prototype.fill()相同。TypedArray是这里的类型化数组类型之一。
语法
typedarray.fill(value[, start = 0[, end = this.length]])
参数
- value
- 用来填充类型化数组元素的值。
- start
- 可选参数。起始索引,默认值为 0。
- end
- 可选参数。终止索引(填充范围不包含此索引),默认值为this.length。
返回值
修改后的类型化数组。
描述
将被元素填充的区间是[start,end)。
fill 方法接受三个参数value,start以及end。start和end参数是可选的,默认值分别为0和this.length。
如果start参数是负值,它会被视为length+start,其中length是类型化数组的长度。如果end参数是负值,它会被视为length+end。
示例
new Uint8Array([1, 2, 3]).fill(4); // Uint8Array [4, 4, 4] new Uint8Array([1, 2, 3]).fill(4, 1); // Uint8Array [1, 4, 4] new Uint8Array([1, 2, 3]).fill(4, 1, 2); // Uint8Array [1, 4, 3] new Uint8Array([1, 2, 3]).fill(4, 1, 1); // Uint8Array [1, 2, 3] new Uint8Array([1, 2, 3]).fill(4, -3, -2); // Uint8Array [4, 2, 3]
兼容实现
由于并没有一个名为TypedArray的全局变量,我们必须“按需添加”兼容实现。请配合Array.prototype.fill()的兼容实现使用以下的“兼容实现”
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill
if (!Uint8Array.prototype.fill) {
  Uint8Array.prototype.fill = Array.prototype.fill;
}
