Home  >  Article  >  Web Front-end  >  How to use copyWithin() in js to copy part of an array

How to use copyWithin() in js to copy part of an array

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-08-11 11:16:032694browse

In the previous article, we learned about how to connect arrays. Please see "How to connect js arrays". This time we will learn how to use copyWithin() to copy part of an array. You can refer to it if necessary.

What should we do when we want to copy a part of the array and put the copied part back into the original array?

Let’s look at a small example first.

The result of this little chestnut is

How to use copyWithin() in js to copy part of an array

You can see this result, the first one is different from the last two results. . So let's go take a look at this code. The previous steps were to create arrays and output arrays normally, and there is nothing wrong here. Looking back, we used the copyWithin() method, and then output the array after using this method. Later, we output the original array once to see if there is anything different.

Okay, let’s take a look at this method.

copyWithin()The method shallowly copies a part of the array to another location in the same array and returns it without changing the length of the original array.

Let’s take a look at the syntax of this method.

数组名称.copyWithin(复制序列到该位置,开始复制元素的起始位置,开始复制元素的结束位置)

If the value of the copied sequence to this position is greater than arr.length, copying will not occur. If the value copied from the sequence to that position is after the starting position of the copied element, the copied sequence will be modified to conform to arr.length.

The copyWithin() method does not require that this value must be an array object; in addition, copyWithin() is a mutable method that can change the object itself and return it, not just a copy of it. The copyWithin() function is designed as a generic function and does not require that its value must be an array object. copyWithin() is a variable method. It does not change the length of this file, but it changes its contents and creates new properties if necessary.

That’s all. If you need it, you can read: javascript advanced tutorial

The above is the detailed content of How to use copyWithin() in js to copy part of an array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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