typedArray.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]Polyfill
由于并没有一个名为TypedArray的全局变量,我们必须“按需添加”兼容实现。请配合Array.prototype.fill()的兼容实现使用以下的“兼容实现”
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill
if (!Uint8Array.prototype.fill) {
Uint8Array.prototype.fill = Array.prototype.fill;
}规范
Specification | Status | Comment |
|---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'TypedArray.prototype.fill' in that specification. | Standard | Initial definition. |
ECMAScript 2017 Draft (ECMA-262)The definition of 'TypedArray.prototype.fill' in that specification. | Draft | |
浏览器兼容性
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
Basic support | 45 | 37 (37) | No support | 32 | No support |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
Basic support | No support | No support | 37 (37) | No support | No support | No support |
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

