奋斗30天Javascript之ECMAScript 6 入门之copyWithin() 方法(part20)

本文摘抄自阮一峰老師的《ECMAScript 6 入门》一文

copyWithin() 

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

语法:

array.copyWithin(target, start, end)
  1. target(必需):从该位置开始替换数据。如果为负值,表示倒数。
  2. start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。
  3. end(可选):到该位置前停止读取数据, 默认为 array.length。如果为负值,表示倒数。

这三个参数都应该是数值,如果不是,会自动转为数值。

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

<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {  
    document.getElementById("demo").innerHTML = fruits.copyWithin(2,0);
}
</script>

結果為:沒點擊點我之前

點擊點我之後:

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

<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi", "Papaya"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {  
    document.getElementById("demo").innerHTML = fruits.copyWithin(2,0,2);
}
</script>

點擊之前:

點擊之後:

这三个参数都应该是数值,如果不是,会自动转为数值。

[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]

上面代码表示将从 3 号位直到数组结束的成员(4 和 5),复制到从 0 号位开始的位置,结果覆盖了原来的 1 和 2。

下面是更多例子。

// 将3号位复制到0号位
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

// -2相当于3号位,-1相当于4号位
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]

// 将3号位复制到0号位
[].copyWithin.call({length: 5, 3: 1}, 0, 3)
// {0: 1, 3: 1, length: 5}

// 将2号位到数组结束,复制到0号位
let i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// 对于没有部署 TypedArray 的 copyWithin 方法的平台
// 需要采用下面的写法
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

猜你喜欢

转载自blog.csdn.net/weixin_41406727/article/details/88842471