JavaScript - TypedArray keys() 方法
JavaScript TypedArray keys() 方法返回一个数组迭代器对象,其中包含类型数组每个索引的键。 JavaScript 中的 key 是用于访问对象中值的唯一标识符。
语法
以下是 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

