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

Array.prototype.fill() - JavaScript | MDN

Esta pgina foi traduzida do ingls pela comunidade. Saiba mais e junte-se comunidade 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 setembro de 2015.

O mtodo fill() preenche todos os valores do array a partir do ndice inicial a um ndice final com um valor esttico.

In this article

Sintaxe

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

Parmetros

valor

Valor para preencher o array.

nicio

Opcional. ndice inicial.

fim

Opcional. ndice final.

Descrio

O intervalo de preenchimento dos elementos [incio, fim).

O mtodo fill pode receber at trs argumentos valor, nicio e fim. Os argumentos nicio e fim so opcionais com valor padro 0 (valor) e o tamanho do objeto (fim).

Se o nicio for negativo, ele ser tratado como tamanho + nicio onde tamanho o tamanho total do array. Se o fim for negativo, ele ser tratado como tamanho + fim.

A funo fill intencionalmente genrica, ele no precisa que o valor do this seja um objeto Array.

O mtodo fill um mtodo mutvel, ele ir mudar o objeto em si, e retorn-lo, no somente uma cpia 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;
  };
}

Especificaes

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

Compatibilidade com navegadores

[1] Comeando com Chrome 36, isto era disponvel com uma mudana nas preferencias. Em chrome://flags, ativar a entrada "Enable Experimental JavaScript".

Ver tambm


Web Proxy Viewer  |  New URL  |  Original Page