JavaScript typedArray.copyWithin()用法示例

2021年5月6日17:04:26 发表评论 121 次浏览

typedArray.copyWithin()是JavaScript中的内置函数, 用于在同一typedArray中的指定位置复制typedArray的某些元素。

语法如下:

typedArray.copyWithin(target, start, end)

参数:它接受下面指定的三个参数-

目标:这是从中复制元素的起始索引位置。

start:这是从其开始复制元素的起始索引位置, 其默认值为typedArray的起始索引。

end:它是可选的, 它是要复制的元素之前的结束位置索引, 并且其默认值是typedArray的结尾。

返回值:复制过程完成后, 它将返回修改后的数组。

<>

JavaScript代码显示此功能的工作方式:

代码1:

<script>
  
    //Constructing a new typedArray "A"
    //with some elements
    const A = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
  
    //Calling copyWithin function to copy 
    //element from index position 0 and
    //element from index 4 to 5
    A.copyWithin(0, 4, 5);
  
    //Printing a new modified array
    document.write(A);
     
</script>

输出如下:

25, 10, 15, 20, 25, 30, 35, 40

代码2:

<script>
  
    //Constructing some new typedArrays
    //with some elements
    const A = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
    const B = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
    const C = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
    const D = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
    const E = new Uint8Array([ 5, 10, 15, 20, 25, 30, 35, 40 ]);
  
    //Calling copyWithin function with different
    //parameters
    a = A.copyWithin(0, 5);
    b = B.copyWithin(1, 4);
    c = C.copyWithin(0, 4, 5);
    d = D.copyWithin(2, 3, 5);
    e = E.copyWithin(0, 1, 4);
  
    //Printing new modified arrays
    document.write(a + "<br>" );
    document.write(b + "<br>" );
    document.write(c + "<br>" );
    document.write(d + "<br>" );
    document.write(e);
     
</script>

输出如下:

30, 35, 40, 20, 25, 30, 35, 40
5, 25, 30, 35, 40, 30, 35, 40
25, 10, 15, 20, 25, 30, 35, 40
5, 10, 20, 25, 25, 30, 35, 40
10, 15, 20, 20, 25, 30, 35, 40

一盏木

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: