7

js使用copyWithin()复制数组一部分

 2 years ago
source link: https://www.fly63.com/article/detial/11396
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

当我们当我们想要复制数组之间的一部分,又想把这个复制出来的放回到原数组的时候该怎么办呢?这里就需要使用js中es6新方法copyWithin()。

定义和用法

copyWithin() 方法用于从数组的指定位置拷贝元素到数组的另一个指定位置中。

语法

array.copyWithin(target, start, end)
参数描述target必需。复制到指定目标索引位置。start可选。元素复制的起始位置。end可选。停止复制的索引位置 (默认为 array.length)。如果为负值,表示倒数。

copyWithin拷贝数组内部的成员:

  1. 第一个参数表示复制的位置
  2. 第二个参数表示复制的起始位置
  3. 第三个参数表示复制的结束位置(不包含)

浏览器支持

6267934c0ddca.jpg

复制数组的前面两个元素到后面两个元素上:

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2,0);
</script>

输出结果:

Banana,Orange,Banana,Orange

复制数组的前面两个元素到第三和第四个位置上:

var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi", "Papaya"];
fruits.copyWithin(2,0,2);

运行结果:

Banana,Orange,Banana,Orange,Kiwi,Papaya

如果复制序列到该位置的值大于arr.length,将会不发生拷贝。如果复制序列到该位置的值在开始复制元素的起始位置之后,复制的序列将被修改以符合 arr.length。

copyWithin()方法不要求其此值必须是数组对象;此外,copyWithin()是一个可变方法,可以更改对象本身并返回它,而不仅仅是它的副本。copyWithin()函数设计为泛型函数,不要求其此值必须是数组对象。copyWithin()是一个变量方法。它不会更改此文件的长度,但会更改其本身的内容,并在必要时创建新属性。

链接: https://www.fly63.com/article/detial/11396


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK