Array对象属性详解2-copyWithin

Array对象属性

Array对象属性二( copyWithin() - ES6)

从数组的指定位置拷贝元素到数组的另一个指定位置中,改变当前数组(暂时没想到这个方法可以用来干啥)

语法

array.copyWithin(target, start, end)

参数 描述
target 必需。复制到指定目标索引位置。
start 可选。元素复制的起始位置。
end 可选。停止复制的索引位置 (默认为 array.length)。如果为负值,表示倒数。
备注 其实这三个参数就是,把数组的 start位置-end位置 之间的元素(包含start,不包含end,例start=2,end=3,就是第2个元素,不包括第3个),插入数组的 第target索引 位置,索引从0开始,如果 start = end,数组不变,start和end负数代表从右数
let words=["a","b","c","d","e","f"];
words.copyWithin(2);
console.log(words);  
//输出结果(复制了a、b 2个值到第0位,然后在数组长度不变的情况下,复制全部数组):
["a", "b", "a", "b", "c", "d"]
let words=["a","b","c","d","e","f"];
words.copyWithin(2,1);
console.log(words);
//输出结果(从第1位开始复制,复制了整个数组,截取显示到数组最长):
["a", "b", "b", "c", "d", "e"]
let words=["a","b","c","d","e","f"];
words.copyWithin(2,1,5);
console.log(words);
//输出结果(从第1位开始复制,到第5-1位复制完,插入到第2个索引后面)
["a", "b", "b", "c", "d", "e"]
words.copyWithin(2,1,1);
//输出结果(从第1位开始复制,到第1位又结束了,相当于没复制,数组不变)
["a", "b", "c", "d", "e", "f"]

资料借鉴:
JavaScript copyWithin() 方法

猜你喜欢

转载自blog.csdn.net/siwangdexie_copy/article/details/83014206