JavaScript typedArray.slice()用法示例

2021年5月3日18:15:20 发表评论 108 次浏览

typedArray.slice()是JavaScript中的内置函数, 用于返回给定typedArray的部分元素。

typedArray.slice(begin, end)

参数:它采用下面指定的两个参数-

begin:它是开始索引, 也可以是负数。

end:这是结束索引, 此处slice提取直到(但不包括)结束索引的元素。

返回值:

它返回一个包含提取元素的新typedArray。

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

<script>
  
   //Creating some typedArray containing same values
   const A = new Uint8Array([ 5, 10, 15, 20, 25 ]);
   const B = new Uint8Array([ 5, 10, 15, 20, 25 ]);
   const C = new Uint8Array([ 5, 10, 15, 20, 25 ]);
   const D = new Uint8Array([ 5, 10, 15, 20, 25 ]);
   const E = new Uint8Array([ 5, 10, 15, 20, 25 ]);
   const F = new Uint8Array([ 5, 10, 15, 20, 25 ]);
  
   //Calling slice function with starting and ending index
   var a = A.slice(1, 2);
   var b = B.slice(0, 3);
   var c = C.slice(4);
   var d = D.slice(0
    
   //Here index is negative so it extract element
   //from the end of the typedArray
   var e = E.slice(-2);
   var f = F.slice();
  
   //Printing the extracted arrays
   document.write(a + "<br>" );
   document.write(b + "<br>" );
   document.write(c + "<br>" );
   document.write(d + "<br>" );
   document.write(e + "<br>" );
   document.write(f);
    
</script>

输出如下:

10
5, 10, 15
25
5, 10, 15, 20, 25
20, 25
5, 10, 15, 20, 25

一盏木

发表评论

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