Movatterモバイル変換


[0]ホーム

URL:


  1. Tecnologia Web para desenvolvedores
  2. JavaScript
  3. Referência JavaScript
  4. Objetos Globais
  5. Array
  6. Array.prototype.fill()

Esta página foi traduzida do inglês pela comunidade.Saiba mais e junte-se à comunidade 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 ⁨setembro de 2015⁩.

O métodofill() preenche todos os valores do array a partir do índice inicial a um índice final com um valor estático.

Sintaxe

arr.fill(valor[, ínicio = 0[, fim = this.length]])

Parâmetros

valor

Valor para preencher o array.

ínicio

Opcional. Índice inicial.

fim

Opcional. Índice final.

Descrição

O intervalo de preenchimento dos elementos é [início,fim).

O métodofill pode receber até três argumentosvalor,ínicio efim. Os argumentosínicio efim são opcionais com valor padrão0 (valor) e o tamanho do objeto(fim).

Se oínicio for negativo, ele será tratado comotamanho + ínicio ondetamanho é o tamanho total do array. Se ofim for negativo, ele será tratado comotamanho + fim.

A funçãofill é intencionalmente genérica, ele não precisa que o valor do this seja um objeto Array.

O métodofill é um método mutável, ele irá mudar o objeto em si, e retorná-lo, não somente uma cópia do objeto.

Exemplos

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, -2); // [4, 2, 3][1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3]Array(3).fill(4); // [4, 4, 4][].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}

Polyfill

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

Especificações

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

Compatibilidade com navegadores

[1] Começando com Chrome 36, isto era disponível com uma mudança nas preferencias. Em chrome://flags, ativar a entrada "Enable Experimental JavaScript".

Ver também

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp