A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin below:

Array.prototype.copyWithin() - JavaScript | MDN

Array.prototype.copyWithin()

Baseline Widely available

El método copyWithin() transfiere una copia plana de una sección a otra dentro del mismo array ( o contexto similar ), sin modificar su propiedad length y lo devuelve.

Pruébalo
const array1 = ["a", "b", "c", "d", "e"];

// Copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// Expected output: Array ["d", "b", "c", "d", "e"]

// Copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// Expected output: Array ["d", "d", "e", "d", "e"]
Sintaxis
arr.copyWithin(target)
arr.copyWithin(target, start)
arr.copyWithin(target, start, end)
Parámetros
target

Índice basado en cero que establece en dónde dentro de la secuencia original se insertará la secuencia copiada. Si es negativo, target se contará desde el final. -1 es el último elemento, -2 el penúltimo, etc.

Si target es igual o mayor que arr.length, no se copiará nada. Si target es posicionado después de start, la secuencia copiada se recortará para que encaje con arr.length.

start Opcional

Índice basado en cero a partir del cual comenzar la copia de elementos. Si es negativo, start comenzará a contarse desde el final.

Si start es omitido, copyWithin copiará desde el principio (por defecto es 0).

end Opcional

Índice basado en cero hasta el cual se copiarán los elementos. copyWithin copiará hasta pero sin incluir el end. Si es negativo, end será contado desde el final.

Si end es omitido, copyWithin copiará hasta el final ( por defecto es arr.length).

Valor de retorno

El array modificado.

Descripción

copyWithin es similar a la función memmove de C y C++ , siendo altamente eficiente para desplazar los datos en un Array o TypedArray. La secuencia de datos es leída y escrita en una sola operación; la escritura será correcta incluso en el caso de que la zona de lectura y el destino de escritura se solapen.

La función copyWithin es intencionadamente genérica, permitiendo que se aplique en contextos en los cuales this no sea necesariamente un objeto Array.

El método copyWithin es un método mutador. No altera la propiedad length de this, pero cambiará su contenido y creará nuevas propiedades si es necesario.

Ejemplos

En los siguientes ejemplos céntrate en los siguientes aspectos:

[1, 2, 3, 4, 5].copyWithin(-2);
// [1, 2, 3, 1, 2]

[1, 2, 3, 4, 5].copyWithin(0, 3);
// [4, 5, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(0, 3, 4);
// [4, 2, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(-2, -3, -1);
// [1, 2, 3, 3, 4]

A continuación se aplica en el contexto de un objeto array-like:

[].copyWithin.call({ length: 5, 3: 1 }, 0, 3);
// {0: 1, 3: 1, length: 5}

Lo que sigue ahora son las subclases tipadas de Array en ES6:

// Arrays tipados en ES6. Son subclases de Array
var i32a = new Int32Array([1, 2, 3, 4, 5]);

i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// En plataformas que todavía no siguen la norma ES6:
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]
Polyfill
if (!Array.prototype.copyWithin) {
  Array.prototype.copyWithin =
    // Array: Number[, Number[, Number]]
    function copyWithin(target, start, stop) {
      var positiveT = target >= 0,
        positiveS = (start = start | 0) >= 0,
        length = this.length,
        zero = 0,
        r = function () {
          return (+new Date() * Math.random()).toString(36);
        },
        delimiter = "\b" + r() + "-" + r() + "-" + r() + "\b",
        hold;

      stop = stop || this.length;
      hold = this.slice
        .apply(
          this,
          positiveT ? [start, stop] : positiveS ? [start, -target] : [start],
        )
        .join(delimiter);

      return (
        this.splice.apply(
          this,
          positiveT
            ? [target, stop - start, hold]
            : positiveS
              ? [target, stop, hold]
              : [target, start, hold],
        ),
        this.join(delimiter).split(delimiter).slice(zero, length)
      );
    };
}
Especificaciones Compatibilidad con navegadores Ver también

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4