WebGL Tutorial
and more

fill

撰写时间:2024-03-05

最新修订:2024-03-09

fill

用数值填充数组。改变原数组。

原型

*[]fill
  • *value
  • numberstart
  • numberend

参数

value
要填充的数值。
start
从该索引值的位置开始填充。
end
填充结束位置的索引值。该位置的元素不在填充的范围之内。

返回值

返回填充后的数组。是原来数组的引用。

说明

fill方法将本数组startend位置内的数据进行填充为value

该方法属于在原地直接修改原来的数组内容,并返回原来数组的引用。

例子

填充时的内部细节

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.fill(100, 4, 6); console.log(res); console.log(arr);

参数start的索引值为4,该索引值所在元素的值为25,参数end的值为6,不含在要填充的范围内。因此只有第4个到第5个索引位置的25, 30被选入要填充的范围。

第1个参数value指定了要填充的数值。该值为100,表示将所选取的2个数组元素的数值改为100。填充后的数组res就变成了:

[5, 10, 15, 20, 100, 100, 35]

而原来的数组arr的内容为:

[5, 10, 15, 20, 100, 100, 35]

说明fill方法将改变原来的数组内容。其返回的实例是原来数组的引用。

console.log(arr === res); // true

参数start及end超出范围时不会填充

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.fill(100, 50, 55); console.log(res);

上面代码准备将第50个至第55个索引值的元素填充为数值100。结果为:

[5, 10, 15, 20, 25, 30, 35]

由于指定的位置超出原数组范围,因此不会发生填充行为。

参数start及end可省略

当参数startend均省略时,默认将填充所有的数组元素。

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.fill(100); console.log(res); // [100, 100, 100, 100, 100, 100, 100]

当只有参数end被省略时,将选取从参数start之后的全部元素。

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.fill(100, 0); // [5, 10, 100, 100, 100, 100, 100]

参数start及end可为负数

当参数start为负数而end省略时,将选取从倒数第start个位置开始的所有剩余元素。

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.fill(100, -2); console.log(res); // [5, 10, 15, 20, 25, 100, 100];

当参数startend均为负数,end的位置应在start位置的右边。否则,违背逻辑,则不会产生填充动作。

let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.fill(100, -2, -2); console.log(res); // [5, 10, 15, 20, 25, 30, 35] <- no filling // or let arr = [5, 10, 15, 20, 25, 30, 35]; let res = arr.fill(100, -2, -3); console.log(res); // [5, 10, 15, 20, 25, 30, 35] <- no filling

参见

  1. copyWithin

参考资源

  1. ECMA 262: Array Objects