Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the usage of Array.copyWithin() function in ES6

巴扎黑
Release: 2017-09-18 09:27:27
Original
2152 people have browsed it

ES6 adds the copyWithin function to Array, which is used to operate the current array itself and copy and overwrite elements at certain positions to other positions. The following focuses on introducing the usage of the Array.copyWithin() function in ES6. Friends who need it can refer to

ES6 adds the copyWithin function to Array, which is used to operate the current array itself and to copy certain positions. The element is copied and overlaid elsewhere.


Array.prototype.copyWithin(target, start = 0, end = this.length)
Copy after login

This function has three parameters.

target: destination starting position.

start: The starting position of the copy source, which can be omitted or a negative number.

end: The end position of the copy source, which can be omitted or a negative number. The actual end position is end-1.

Example:

Copy and overwrite the 3rd element (starting from 0) to the 5th element to the position starting from the 1st position.

The red block below is the starting position of the copy target, and the yellow block is the copy source.


const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
arr1.copyWithin(1, 3, 6)
console.log('%s', JSON.stringify(arr1))
Copy after login

Result:

[1,4,5,6,5,6,7,8,9,10,11]

Both start and end can be omitted.

The omission of start means starting from 0, and the omission of end means the length value of the array.

If the target position is not enough, cover as much as you can.


const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
arr2.copyWithin(3)
console.log('%s', JSON.stringify(arr2))
Copy after login

Result:

[1,2,3,1,2,3,4,5,6,7,8]

Both start and end can be negative numbers, and the negative number indicates the number counted from the right.


const arr3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
arr3.copyWithin(3, -3, -2)
console.log('%s', JSON.stringify(arr3))
Copy after login

Result:

[1,2,3,9,5,6,7,8,9,10,11]

The above is the detailed content of Detailed explanation of the usage of Array.copyWithin() function in ES6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!