JavaScript - TypedArray keys() 方法



JavaScript TypedArray 的keys()方法返回一個數組迭代器物件,其中包含型別化陣列中每個索引的鍵。JavaScript 中的是用於訪問物件中值的唯一識別符號。

語法

以下是 JavaScript TypedArray keys()方法的語法:

keys()

引數

  • 它不接受任何引數。

返回值

此方法返回一個新的陣列迭代器物件。

示例

示例 1

在下面的程式中,我們使用 JavaScript TypedArray 的keys()方法來檢索此型別化陣列[10, 20, 30, 40, 50]的陣列迭代器物件。

<html>
<head>
   <title>JavaScript TypedArray keys() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([10, 20, 30, 40, 50]);
      document.write("The typed arrays is: ", T_array);
      document.write("<br>The T_array.keys() method returns: ", T_array.keys());
   </script>    
</body>
</html>

輸出

上述程式在輸出中返回“[object Array Iterator]”。

The typed arrays is: 10,20,30,40,50
The T_array.keys() method returns: [object Array Iterator]

示例 2

以下是 JavaScript TypedArray keys()的另一個示例。我們使用此方法來檢索包含此型別化陣列[1, 2, 3, 4, 5, 6, 7, 8]的每個索引的鍵的陣列迭代器物件。

<html>
<head>
   <title>JavaScript TypedArray keys() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([10, 20, 30, 40, 50]);
      document.write("The typed arrays is: ", T_array);
      document.write("<br>The T_array.keys() method returns: ", T_array.keys());
      const arrayKeys = T_array.keys();
      document.write("<br>The typed array keys and respected values are: <br>")
      for(const n of arrayKeys){
         document.write("Key = ", n, " , Value = ", T_array[n], "<br>");
      }
   </script>    
</body>
</html>

輸出

執行上述程式後,它將顯示每個索引上的鍵以及值,如下所示:

The typed arrays is: 10,20,30,40,50
The T_array.keys() method returns: [object Array Iterator]
The typed array keys and respected values are:
Key = 0 , Value = 10
Key = 1 , Value = 20
Key = 2 , Value = 30
Key = 3 , Value = 40
Key = 4 , Value = 50

示例 3

在此程式中,我們使用keys()方法來檢索型別化陣列[1, 2, 3, 4, 5]中每個索引的鍵的陣列迭代器物件。然後,我們將所有鍵儲存在一個變數中並執行另一種迭代。

<html>
<head>
   <title>JavaScript TypedArray keys() Method</title>
</head>
<body>
   <script>
      const T_array = new Uint8Array([1, 2, 3, 4, 5]);
      document.write("The typed arrays is: ", T_array);
      const allKeys = T_array.keys();
      document.write("<br>");
      document.write("Key1 = ", allKeys.next().value, "<br>");
      document.write("Key2 = ", allKeys.next().value, "<br>");
      document.write("Key3 = ", allKeys.next().value, "<br>");
      document.write("Key4 = ", allKeys.next().value, "<br>");
      document.write("Key5 = ", allKeys.next().value);
   </script>    
</body>
</html>

輸出

執行上述程式後,它將返回每個索引的鍵,如下所示:

The typed arrays is: 1,2,3,4,5
Key1 = 0
Key2 = 1
Key3 = 2
Key4 = 3
Key5 = 4
廣告