當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JavaScript Array copyWithin()用法及代碼示例

JavaScript Array copyWithin() 方法淺拷貝數組元素到數組中的另一個位置,覆蓋現有值。

用法:

arr.copyWithin(target, start, end)

這裏,arr 是一個數組。

參數:

copyWithin() 方法包含:

  • target - 要將元素複製到的索引位置。
  • start(可選)- 開始複製元素的索引位置。如果省略,它將從索引中複製0.
  • end(可選)- 結束複製元素的索引位置。 (exclusive) 如果省略,它將複製到最後一個索引。

注意:

  • 如果任何參數為負數,則索引將從倒數開始計算。例如,-1代表最後一個元素,依此類推。
  • 如果target值在之後start, 複製的序列被修剪以適應arr.length.

返回:

  • 複製元素後返回修改後的數組。

注意

  • 此方法會覆蓋原始數組。
  • 此方法不會更改原始數組的長度。

示例:使用copyWithin() 方法

let array = [1, 2, 3, 4, 5, 6];

// target: from second-to-last element, start: 0, end: array.length
let returned_arr = array.copyWithin(-2);
console.log(returned_arr); // [ 1, 2, 3, 4, 1, 2 ]
// modifies the original array
console.log(array); // [ 1, 2, 3, 4, 1, 2 ]

array = [1, 2, 3, 4, 5, 6];
// target: 0, start copying from 5th element
array.copyWithin(0, 4);
console.log(array); // [ 5, 6, 3, 4, 5, 6 ]

array = [1, 2, 3, 4, 5, 6];
// target: 1, start copying from 3rd element to second-to-last element
array.copyWithin(1, 2, -1); // -1 = last element (exclusive)
console.log(array); // [ 1, 3, 4, 5, 5, 6 ]

輸出

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

相關用法


注:本文由純淨天空篩選整理自 Javascript Array copyWithin()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。