码迷,mamicode.com
首页 > 其他好文 > 详细

ES6,Array.copyWithin的用法

时间:2017-09-15 18:58:08      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:红色   target   pre   pyw   参数   within   其他   函数   class   

ES6为Array增加了copyWithin函数,用于操作当前数组自身,用来把某些个位置的元素复制并覆盖到其他位置上去。

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

该函数有三个参数。

target:目的起始位置。

start:复制源的起始位置,可以省略,可以是负数。

end:复制源的结束位置,可以省略,可以是负数,实际结束位置是end-1。

 

例: 

把第3个元素(从0开始)到第5个元素,复制并覆盖到以第1个位置开始的地方。

下面的红色块是复制目标的起始位置,黄色块为复制的源。

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

结果:

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

 

start和end都是可以省略。

start省略表示从0开始,end省略表示数组的长度值。

目标的位置不够的,能覆盖多少就覆盖多少。

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

结果:

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

 

start和end都可以是负数,负数表示从右边数过来第几个。

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

结果:

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

 

end

ES6,Array.copyWithin的用法

标签:红色   target   pre   pyw   参数   within   其他   函数   class   

原文地址:http://www.cnblogs.com/kongxianghai/p/7527177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!