JavaScript - TypedArray entries() 方法
JavaScript TypedArray 的 entries() 方法返回一个数组迭代器对象,该对象包含类型化数组中每个索引对应的键值对。此特定方法并非适用于所有数组,只能在类型化数组的实例上调用。
TypedArray 对象的 entries() 和 values() 方法类似。两者都返回一个数组类型的迭代器对象,唯一的区别在于 values() 方法返回的对象在每个索引处只包含一个元素。而entries() 方法返回的迭代器对象包含键值对。
语法
以下是 JavaScript TypedArray entries() 方法的语法 -
entries()
参数
它不接受任何参数。
返回值
此方法返回一个新的数组可迭代对象。
示例
示例 1
以下程序演示了 JavaScript TypedArray entries() 方法的用法。
<html>
<head>
<title>JavaScript TypedArray entries() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([1, 2, 3, 4, 5]);
document.write("The original typed array: ", T_array);
//使用 entries() 方法
let new_array = T_array.entries();
document.write("<br>The new_array iterator object: ", new_array);
</script>
</body>
</html>
输出
上述程序返回一个新的"对象数组迭代器"。
The original typed array: 1,2,3,4,5 The new_array iterator object: [object Array Iterator]
示例 2
以下是 JavaScript TypedArray entries() 方法的另一个示例。使用此方法,我们尝试从此类型数组 [10, 20, 30, 40, 50] 中检索一个新的对象数组迭代器。我们在对象数组迭代器上使用 next().value 来检索特定元素。
<html>
<head>
<title>JavaScript TypedArray entries() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([10, 20, 30, 40, 50]);
document.write("The original typed array: ", T_array);
//使用 entries() 方法
let new_array = T_array.entries();
document.write("<br>The new_array iterator object: ", new_array);
document.write("<br>The new_array.next().value returns: ", new_array.next().value);
//expected output 10.
</script>
</body>
</html>
输出
执行上述程序后,返回键为 0,值为 10。
The original typed array: 10,20,30,40,50 The new_array iterator object: [object Array Iterator] The new_array.next().value returns: 0,10
示例 3
在此示例中,我们使用 for...of 循环来遍历 entries() 方法返回的对象数组迭代器的每个元素。
<html>
<head>
<title>JavaScript TypedArray entries() Method</title>
</head>
<body>
<script>
const T_array = new Uint8Array([10, 20, 30, 40, 50]);
document.write("The original typed array: ", T_array);
//使用 entries() 方法
let new_array = T_array.entries();
document.write("<br>The object array iterator values: ");
//使用 for...of 循环
for(const i of new_array){
document.write("<br>Kyes = ", i[0], " Values = ", i[1]);
}
</script>
</body>
</html>
输出
上述程序执行后,将返回对象数组迭代器每个元素的键值对,如下所示:
The original typed array: 10,20,30,40,50 The object array iterator values: Kyes = 0 Values = 10 Kyes = 1 Values = 20 Kyes = 2 Values = 30 Kyes = 3 Values = 40 Kyes = 4 Values = 50

