Array.prototype.copyWithin
The copyWithin() method shallow copies part of an array
to another location in the same array and returns it without modifying its length.
Syntax
copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)
Parameters
target- : Zero-based index at which to copy the sequence to, converted to an integer.
- Negative index counts back from the end of the array — if
target < 0,target + array.lengthis used. - If
target < -array.length,0is used. - If
target >= array.length, nothing is copied. - If
targetis positioned afterstartafter normalization, copying only happens until the end ofarray.length(in other words,copyWithin()never extends the array).
- Negative index counts back from the end of the array — if
- : Zero-based index at which to copy the sequence to, converted to an integer.
startoptional- : Zero-based index at which to start copying elements from, converted to an integer.
- Negative index counts back from the end of the array — if
start < 0,start + array.lengthis used. - If
start < -array.lengthorstartis omitted,0is used. - If
start >= array.length, nothing is copied.
- Negative index counts back from the end of the array — if
- : Zero-based index at which to start copying elements from, converted to an integer.
endoptional- : Zero-based index at which to end copying elements from, converted to an integer.
copyWithin()copies up to but not includingend.- Negative index counts back from the end of the array — if
end < 0,end + array.lengthis used. - If
end < -array.length,0is used. - If
end >= array.lengthorendis omitted,array.lengthis used, causing all elements until the end to be copied. - If
endis positioned before or atstartafter normalization, nothing is copied.
- Negative index counts back from the end of the array — if
- : Zero-based index at which to end copying elements from, converted to an integer.
Return value
The modified array.
Description
The copyWithin() method works like C and C++'s memmove, and is a high-performance method to shift the data of an Array. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap.
The copyWithin() method is a mutating method. It does not alter the length of this, but it will change the content of this and create new properties or delete existing properties, if necessary.
The copyWithin() method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are deleted and also become empty slots.
The copyWithin() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.