copyWithin()方法將數組的一部分複製到同一數組並返回它,而無需修改其大小,即在同一數組內複製數組的數組元素。
用法:
array.copyWithin(target, start, end) 參數: target: The index position to copy the elements to(Required). start:It is optional. The index position to start copying elements from (default is 0). end: It is optional. The index position to stop copying elements from (default is array.length). 返回值: It returns the modified array.
JavaScript版本:ECMAScript 6
瀏覽器支持:
Chrome 45.0 Edge 12.0 Firefox 32.0 Opera 32.0 IE No
Examples
程序1:
// Input array
var array = [ 1, 2, 3, 4, 5, 6, 7 ];
// placing at index position 0 the element
// between index 3 and 6
console.log(array.copyWithin(0, 3, 6));
輸出:
Array [4, 5, 6, 4, 5, 6, 7]
程序2:
// Input array
var array = [ 1, 2, 3, 4, 5, 6, 7 ];
// placing from index position 0 the
// element from index 4
console.log(array.copyWithin(0, 4));
輸出:
Array [5, 6, 7, 4, 5, 6, 7]
程序3:
// Input array
var array = [ 1, 2, 3, 4, 5, 6, 7 ];
// placing from index position 3
// the element from index 0
console.log(array.copyWithin(3));
輸出:
Array [1, 2, 3, 1, 2, 3, 4]
應用程序:每當我們需要將任何數組的內容複製到同一數組時,我們都使用javaScript中的array.copyWithin()元素。
// Input array
var array = [ 1, 2, 3, 4, 5, 6, 7 ];
// placing at index position 0 the
// element between index 4 and 5
console.log(array.copyWithin(0, 4, 5));
輸出:
Array [5, 2, 3, 4, 5, 6, 7]
相關用法
- Javascript typedArray.copyWithin()用法及代碼示例
- Javascript array.size()和array.length的區別用法及代碼示例
- Javascript Array.slice()和Array.splice()的區別用法及代碼示例
- Javascript Array pop()用法及代碼示例
- Javascript Array unshift()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 JavaScript | Array copyWithin()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。