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


Javascript typedArray.from()用法及代碼示例


typedArray.from()是JavaScript中的內置函數,用於從普通數組或任何可迭代對象構造新的typedArray。下麵列出了不同typedArray的列表-

  • Int8Array();
  • Uint8Array();
  • Uint8ClampedArray();
  • Int16Array();
  • Uint16Array();
  • Int32Array();
  • Uint32Array();
  • Float32Array();
  • Float64Array();

用法:

typedArray.from(source, mapFn, thisArg)

參數:它接受以下指定的三個參數:


  • source:它是一個普通數組或任何可迭代的對象,可以轉換為typedArray。
  • mapFn:它是可選的,並且是對typedArray的每個元素進行調用的map函數。
  • thisArg:它是可選的,是執行mapFn函數時要使用的值。

返回值:它返回一個新的typedArray實例。
JavaScript代碼顯示此函數的工作方式:
代碼1:

<script> 
  
    // Constructing an iterable object 
    var a = new Set([ 5, 10, 15, 20, 25 ]); 
    var b = new Set([ 1, 2, 3, 4, 5 ]); 
    var c = new Set([ 1, 3, 5, 7, 9 ]); 
    var d = new Set([ 2, 4, 6, 8, 10 ]); 
  
    // Calling from() function 
    A = Uint8Array.from(a); 
    B = Uint8Array.from(b); 
    C = Uint8Array.from(c); 
    D = Uint8Array.from(d); 
  
   // Printing new typedArray instance 
    document.write(A + "<br>"); 
    document.write(B + "<br>"); 
    document.write(C + "<br>"); 
    document.write(D); 
  
</script>

輸出:

5, 10, 15, 20, 25
1, 2, 3, 4, 5
1, 3, 5, 7, 9
2, 4, 6, 8, 10

代碼2:

<script> 
  
    // Calling from() function 
    A = Uint16Array.from('123456'); 
    B = Uint16Array.from('80397418327'); 
  
    // Printing new typedArray instance 
    document.write(A + "<br>"); 
    document.write(B + "<br>"); 
  
</script>

輸出:

1, 2, 3, 4, 5, 6
8, 0, 3, 9, 7, 4, 1, 8, 3, 2, 7

代碼3:

<script> 
  
    // Constructing an iterable object 
    var a = new Set([ 5, 10, 15, 20, 25 ]); 
    var b = new Set([ 1, 2, 3, 4, 5 ]); 
    var c = new Set([ 1, 3, 5, 7, 9 ]); 
    var d = new Set([ 2, 4, 6, 8, 10 ]); 
  
    // Calling from() function 
    A = Uint8Array.from(a, x => x + 1); 
    B = Uint8Array.from(b, x => x + 2); 
    C = Uint8Array.from(c, x => x * 2);   
    D = Uint8Array.from(d); 
  
    // Printing new typedArray instance 
   document.write(A + "<br>"); 
   document.write(B + "<br>"); 
   document.write(C + "<br>"); 
   document.write(D); 
  
</script>

輸出:

6, 11, 16, 21, 26
3, 4, 5, 6, 7
2, 6, 10, 14, 18
2, 4, 6, 8, 10


相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 JavaScript | typedArray.from() with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。