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;
}
规范
| 规范 | 状态 | 注释 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) TypedArray.prototype.fill |
Standard | 最初定义。 |
| ECMAScript Latest Draft (ECMA-262) TypedArray.prototype.fill |
Draft |
浏览器兼容性
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains.
Find out how you can help!
| 特性 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| 基础支持 | 45 | 37 (37) | 未实现 | 32 | 未实现 |
| 特性 | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| 基础支持 | 未实现 | 未实现 | 37 (37) | 未实现 | 未实现 | 未实现 |