[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ja/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

20159

fill() Array

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

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

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

console.log(array.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 < 0 end + array.length
  • end < -array.length 0
  • end >= array.length end undefined array.length
  • end start

value

fill() this this

fill() value

fill() this length

: Array.prototype.fill() Array.prototype.fill()

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

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); //  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

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

ECMAScript 2027 LanguageSpecification
# sec-array.prototype.fill


Web Proxy Viewer  |  New URL  |  Original Page