Movatterモバイル変換


[0]ホーム

URL:


  1. Tecnología web para desarrolladores
  2. JavaScript
  3. Referencia de JavaScript
  4. Objetos globales
  5. Array
  6. Array.prototype.fill()

Esta página ha sido traducida del inglés por la comunidad.Aprende más y únete a la comunidad de MDN Web Docs.

View in EnglishAlways switch to English

Array.prototype.fill()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨septiembre de 2015⁩.

El métodofill() cambia todos los elementos en un arreglo por un valor estático, desde el índice start (por defecto 0) hasta el índice end (por defectoarray.length). Devuelve el arreglo modificado.

Pruébalo

const array1 = [1, 2, 3, 4];// Fill with 0 from position 2 until position 4console.log(array1.fill(0, 2, 4));// Expected output: Array [1, 2, 0, 0]// Fill with 5 from position 1console.log(array1.fill(5, 1));// Expected output: Array [1, 5, 5, 5]console.log(array1.fill(6));// Expected output: Array [6, 6, 6, 6]

Sintaxis

arr.fill(value[, start = 0[, end = this.length]])

Parámetros

value

Valor con el que se va a rellenar el arreglo. (Nótese que todos los elementos en el arreglo tendrán este mismo valor).

startOpcional

Índice inicial, por defecto 0.

endOpcional

Índice final, por defectothis.length.

Valor de retorno

El arreglo modificado, rellenado convalor.

Descripción

  • Sistart es negativo, se interpreta comoarray.length + start.
  • Siend es negativo, se interpreta comoarray.length + end.
  • fill es genérico de forma intencional: no requiere que su valorthis sea un objetoArray.
  • fill es un método mutador: modifica el arreglo sobre el que se invoca; no devuelve una copia de éste.
  • Si el primer parámetro es un objeto, copia su referencia y rellena el arreglo con referencias a dicho objeto.

Ejemplos

js
[1, 2, 3].fill(4); // [4, 4, 4][1, 2, 3].fill(4, 1); // [1, 4, 4][1, 2, 3].fill(4, 1, 2); // [1, 4, 3][1, 2, 3].fill(4, 1, 1); // [1, 2, 3][1, 2, 3].fill(4, 3, 3); // [1, 2, 3][1, 2, 3].fill(4, -3, -2); // [4, 2, 3][1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3][1, 2, 3].fill(4, 3, 5); // [1, 2, 3]Array(3).fill(4); // [4, 4, 4][].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}// Objects by reference.var arr = Array(3).fill({}); // [{}, {}, {}];arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

Polyfill

js
if (!Array.prototype.fill) {  Object.defineProperty(Array.prototype, "fill", {    value: function (value) {      // Pasos 1-2.      if (this == null) {        throw new TypeError("esto es nulo o no definido");      }      var O = Object(this);      // Pasos 3-5.      var len = O.length >>> 0;      // Pasos 6-7.      var start = arguments[1];      var relativeStart = start >> 0;      // Paso 8.      var k =        relativeStart < 0          ? Math.max(len + relativeStart, 0)          : Math.min(relativeStart, len);      // Pasos 9-10.      var end = arguments[2];      var relativeEnd = end === undefined ? len : end >> 0;      // Paso 11.      var final =        relativeEnd < 0          ? Math.max(len + relativeEnd, 0)          : Math.min(relativeEnd, len);      // Paso 12.      while (k < final) {        O[k] = value;        k++;      }      // Paso 13.      return O;    },  });}

Especificaciones

Specification
ECMAScript® 2026 Language Specification
# sec-array.prototype.fill

Compatibilidad con navegadores

Ver también

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp