[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/fill [Back]  [Original]

Array.prototype.fill() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Array.prototype.fill()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 20159.

Array fill()

In this article

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

//  2  4  0
console.log(array1.fill(0, 2, 4));
// Array [1, 2, 0, 0]

//  1  5
console.log(array1.fill(5, 1));
// Array [1, 5, 5, 5]

console.log(array1.fill(6));
// 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 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

0 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]

// 
const arr = Array(3).fill({}); // [{}, {}, {}]
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

fill() 1

1 Octave MATLAB ones()

js
const arr = new Array(3);
for (let i = 0; i < arr.length; i++) {
  arr[i] = new Array(4).fill(1); //  4 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() this length start end value

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

Specification
ECMAScript 2027 LanguageSpecification
# sec-array.prototype.fill


Web Proxy Viewer  |  New URL  |  Original Page