Array.prototype.fill()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 2015 年 9 月以来,该特性已在各大浏览器中可用。

fill() 方法用于更改数组中指定索引范围内的所有元素为某个静态值。它会返回修改后的数组。

试一试

const array = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4
console.log(array.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1
console.log(array.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]

console.log(array.fill(6));
// Expected output: Array [6, 6, 6, 6]

语法

js
fill(value)
fill(value, start)
fill(value, start, end)

参数

value

用于填充数组的值。请注意,数组中的所有元素都将是此确切值:如果 value 是一个对象,则数组中的每个槽都将引用该对象。

start 可选

开始填充的零基索引,已转换为整数

  • 负数索引从数组末尾开始计数——如果 -array.length <= start < 0,则使用 start + array.length
  • 如果 start < -array.length 或省略了 start,则使用 0
  • 如果 start >= array.length,则不会填充任何索引。
end 可选

结束填充的零基索引,已转换为整数fill() 会填充到 end 之前的位置。

  • 负数索引从数组末尾开始计数——如果 -array.length <= end < 0,则使用 end + array.length
  • 如果 end < -array.length,则使用 0
  • 如果 end >= array.lengthend 被省略或为 undefined,则会使用 array.length,导致填充到数组末尾的所有索引。
  • 如果 end 暗示的位置早于或等于 start 暗示的位置,则不会填充任何内容。

返回值

修改后的数组,填充了 value

描述

fill() 方法是一个修改方法。它不会改变 this 的长度,但会改变 this 的内容。

fill() 方法也会用 value 填充稀疏数组中的空槽。

fill() 方法是通用的。它只要求 this 值具有 length 属性。虽然字符串也像数组一样,但此方法不适合应用于它们,因为字符串是不可变的。

注意: 在空数组(length = 0)上使用 Array.prototype.fill() 不会修改它,因为数组没有任何内容可以修改。要在声明数组时使用 Array.prototype.fill(),请确保数组的 length 非零。 参见示例

示例

使用 fill()

js
console.log([1, 2, 3].fill(4)); // [4, 4, 4]
console.log([1, 2, 3].fill(4, 1)); // [1, 4, 4]
console.log([1, 2, 3].fill(4, 1, 2)); // [1, 4, 3]
console.log([1, 2, 3].fill(4, 1, 1)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 3)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, -3, -2)); // [4, 2, 3]
console.log([1, 2, 3].fill(4, NaN, NaN)); // [1, 2, 3]
console.log([1, 2, 3].fill(4, 3, 5)); // [1, 2, 3]
console.log(Array(3).fill(4)); // [4, 4, 4]

// A single object, referenced by each slot of the array:
const arr = Array(3).fill({}); // [{}, {}, {}]
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

使用 fill() 创建一个全为 1 的矩阵

此示例演示了如何创建 Octave 或 MATLAB 中的 ones() 函数类似的、全为 1 的矩阵。

js
const arr = new Array(3);
for (let i = 0; i < arr.length; i++) {
  arr[i] = new Array(4).fill(1); // Creating an array of size 4 and filled of 1
}
arr[0][0] = 10;
console.log(arr[0][0]); // 10
console.log(arr[1][0]); // 1
console.log(arr[2][0]); // 1

使用 fill() 填充空数组

此示例演示了如何填充数组,将所有元素设置为特定值。可以省略 end 参数。

js
const tempGirls = Array(5).fill("girl", 0);

请注意,该数组最初是一个稀疏数组,没有分配索引。fill() 仍然能够填充此数组。

在非数组对象上调用 fill()

fill() 方法读取 thislength 属性,并设置从 startend 的每个整数键属性的值。

js
const arrayLike = { length: 2 };
console.log(Array.prototype.fill.call(arrayLike, 1));
// { '0': 1, '1': 1, length: 2 }

规范

规范
ECMAScript® 2026 语言规范
# sec-array.prototype.fill

浏览器兼容性

另见