| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/fill | [Back] [Original] |
Get to know MDN better
This feature is well established and works across many devices and browser versions. Its been available across browsers since 20159.
Array fill()
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]
fill(value)
fill(value, start)
fill(value, start, end)
value value
start -array.length <= start < 0 start + array.lengthstart < -array.length start 0start >= array.lengthend -array.length <= end < 0 end + array.lengthend < -array.length 0end >= array.lengthend undefined array.lengthend start value
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" }]
1 Octave MATLAB ones()
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
end
const tempGirls = Array(5).fill("girl", 0);
fill() this length start end value
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 |
This page was last modified on 2025714 by MDN contributors.
Arrayat()Array.prototype.concat()Array.prototype.copyWithin()Array.prototype.entries()every()Array.prototype.fill()Array.prototype.filter()Array.prototype.find()Array.prototype.findIndex()findLast()findLastIndex()Array.prototype.flat()flatMap()forEach()Array.prototype.includes()Array.prototype.indexOf()Array.prototype.join()Array.prototype.keys()Array.prototype.lastIndexOf()Array.prototype.map()Array.prototype.pop()Array.prototype.push()Array.prototype.reduce()reduceRight()Array.prototype.reverse()Array.prototype.shift()Array.prototype.slice()some()Array.prototype.sort()Array.prototype.splice()toLocaleString()toReversed()toSorted()toSpliced()Array.prototype.toString()Array.prototype.unshift()Array.prototype.values()with()Array.prototype[Symbol.iterator]()Object/FunctionYour blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |