非常教程

JavaScript参考手册

TypedArray

typedArray.fill

fill()方法将类型化数组中的从起始索引到终止索引内的全部元素。这个方法的算法和 Array.prototype.fill()相同。 TypedArray是这里的类型化数组类型之一。

语法

typedarray.fill(value[, start = 0[, end = this.length]])

参数

value用来填充类型化数组元素的值。start可选参数。起始索引,默认值为 0。end可选参数。终止索引(填充范围不包含此索引),默认值为 this.length

返回值

修改后的类型化数组。

描述

将被元素填充的区间是 [start,end)。

fill 方法接受三个参数 valuestart以及 end。start 和 end参数是可选的,默认值分别为 0this.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

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络