JavaScript TypedArray copyWithin() 方法将同一 TypedArray 中的元素复制到另一个位置,并返回修改后的 TypedArray,而不更改其原始长度。它接受三个参数,其中一个 named 是目标。
如果 target 参数值为负数,它将开始在类型化数组的末尾插入一个元素。例如,如果 target = −1,则该值将插入到当前类型化数组的末尾。
语法
以下是 JavaScript TypedArray copyWithin() 方法的语法 -
copyWithin(target, start, end)
参数
此方法接受名为 'target'、'start' 和 'end' 的三个参数,如下所述 -
- target − 元素开始插入的从 Zero 开始插入的索引(位置)。
- start − 元素开始复制的从零开始的索引。
- end (可选) − 从 零开始的索引,用于复制元素的末尾。该方法会一直复制到末尾,但会排除它。
返回值
此方法返回修改后的 TypedArray,而不更改原始 TypedArray 的长度。
示例 1
如果我们只将 target 和 start 参数传递给此方法,它将开始在指定的目标位置(即 3)插入元素,并从指定的起始位置(即 0)开始从原始 TypedArray 复制元素,直到复制元素的长度等于原始 TypedArray([1, 2, 3, 4, 5, 6, 7, 8]).
<html>
<head>
<title>JavaScript TypedArray copyWithin() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
document.write("Original TypedArray: ", T_array);
const target = 3;
const start = 0;
document.write("<br>Target(start insert) position at: ", target);
document.write("<br>Start copying position at: ", start);
T_array.copyWithin(target, start);
document.write("<br>Modified TypedArray: ", T_array);
</script>
</body>
</html>
输出
上面的程序返回修改后的类型数组为 [1,2,3,1,2,3,4,5]。
Target(start insert) position at: 3
Start copying position at: 0
Modified TypedArray: 1,2,3,1,2,3,4,5
示例 2
如果我们将所有三个参数(target、start 和 end)都传递给此方法,它将开始在指定的目标位置(即 4)插入元素,然后开始从原始 TypedArray 复制元素,从指定的起始位置(即 1)开始,直到(但不包括)指定的结束位置(即 3)。其余元素保持不变。
<html>
<head>
<title>JavaScript TypedArray copyWithin() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 0, 0, 0, 0, 0]);
document.write("Original TypedArray: ", T_array);
const target = 4;
const start = 1;
const end = 3;
document.write("<br>Target(start insert) position at: ", target);
document.write("<br>Start copying position at: ", start);
document.write("<br>End(stop copying) position at: ", end);
T_array.copyWithin(target, start, end);
document.write("<br>Modified TypedArray: ", T_array);
</script>
</body>
</html>
输出
执行上述程序后,返回一个修改后的类型化数组 [1,2,3,0,2,3,0,0]。
Target(start insert) position at: 4
Start copying position at: 1
End(stop copying) position at: 3
Modified TypedArray: 1,2,3,0,2,3,0,0
示例 3
如果目标参数值为负数 (-1),则它将元素插入此 TypedArray [1, 2, 3, 4, 5, 6, 7, 8] 的末尾。
<html>
<head>
<title>JavaScript TypedArray copyWithin() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
document.write("Original TypedArray: ", T_array);
const target = -1;
const start = 1;
const end = 3;
document.write("<br>Target(start insert) position at: ", target);
document.write("<br>Start copying position at: ", start);
document.write("<br>End(stop copying) position at: ", end);
T_array.copyWithin(target, start, end);
document.write("<br>Modified TypedArray: ", T_array);
</script>
</body>
</html>
输出
执行上述程序后,它将返回修改后的 TypedArray 作为 -
Target(start insert) position at: -1
Start copying position at: 1
End(stop copying) position at: 3
Modified TypedArray: 1,2,3,4,5,6,7,2