| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin | [Back] [Original] |
Get to know MDN better
Esta pgina ha sido traducida del ingls por la comunidad. Aprende ms y nete a la comunidad de MDN Web Docs.
This feature is well established and works across many devices and browser versions. Its been available across browsers since septiembre de 2015.
El mtodo copyWithin() transfiere una copia plana de una seccin a otra dentro del mismo array ( o contexto similar ), sin modificar su propiedad length y lo devuelve.
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"]
arr.copyWithin(target) arr.copyWithin(target, start) arr.copyWithin(target, start, end)
targetndice basado en cero que establece en dnde 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 penltimo, etc.
Si target es igual o mayor que arr.length, no se copiar nada. Si target es posicionado despus de start, la secuencia copiada se recortar para que encaje con arr.length.
start Opcionalndice 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 Opcionalndice basado en cero hasta el cual se copiarn 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).
El array modificado.
copyWithin es similar a la funcin memmove de C y C++ , siendo altamente eficiente para desplazar los datos en un Array o TypedArray. La secuencia de datos es leda y escrita en una sola operacin; la escritura ser correcta incluso en el caso de que la zona de lectura y el destino de escritura se solapen.
La funcin copyWithin es intencionadamente genrica, permitiendo que se aplique en contextos en los cuales this no sea necesariamente un objeto Array.
El mtodo copyWithin es un mtodo mutador. No altera la propiedad length de this, pero cambiar su contenido y crear nuevas propiedades si es necesario.
En los siguientes ejemplos cntrate en los siguientes aspectos:
start y end trabajan juntos para decidir qu se copiar. Siempre tienen valor por defecto aunque omitas end, o start y end.target trabaja solo y debe especificarse. Indica el lugar para en el que la copia comenzar a sobreescribir datos existentes. Debe estar dentro de los lmites en el contexto que se aplique.arr.copyWithin( n ) es lo mismo que arr.copyWithin( n, 0, arr.length)[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 continuacin se aplica en el contexto de un objeto array-like:
copyWithin es un mtodo mutador. Por qu se cre esta nueva propiedad? porque mediante el argumento target se especific que la copia deba comenzar a partir de un ndice que no exista!![].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 todava no siguen la norma ES6:
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]
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)
);
};
}
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-array.prototype.copywithin |
This page was last modified on 24 jun 2025 by MDN contributors.
ArrayArray.prototype.at()Array.prototype.concat()Array.prototype.copyWithin()Array.prototype.entries()Array.prototype.every()Array.prototype.fill()Array.prototype.filter()Array.prototype.find()Array.prototype.findIndex()findLast()findLastIndex()Array.prototype.flat()Array.prototype.flatMap()Array.prototype.forEach()Array.prototype.includes()Array.prototype.indexOf()Array.prototype.join()Array.prototype.keys()Array.prototype.lastIndexOf()Array.prototype.map()Array.prototype.pop()Array.prototype.push()Array.prototype.reduce()Array.prototype.reduceRight()Array.prototype.reverse()Array.prototype.shift()Array.prototype.slice()Array.prototype.some()Array.prototype.sort()Array.prototype.splice()Array.prototype.toLocaleString()toReversed()Array.prototype.toSorted()toSpliced()Array.prototype.toString()Array.prototype.unshift()Array.prototype.values()with()Array.prototype[@@iterator]()Object/FunctionYour blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |