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]
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
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
Key1 = 0
Key2 = 1
Key3 = 2
Key4 = 3
Key5 = 4