JavaScript TypedArray entries() 方法返回一个数组迭代器对象,该对象包含类型化数组中每个索引的键和值对。此特定方法不适用于所有数组,只能在类型化数组的实例上调用。
TypedArray 对象的 entries() 和 values() 方法类似。两者都返回 array 类型的迭代器对象,它们之间的唯一区别是 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);
//using the entries() method
let new_array = T_array.entries();
document.write("<br>The new_array iterator object: ", new_array);
</script>
</body>
</html>
输出
上面的程序返回一个新的 “object Array iterator”。
The original typed array: 1,2,3,4,5
The new_array iterator object: [object Array Iterator]
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);
//using the entries() method
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>
输出
执行上述程序后,返回 key 为 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
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);
//using the entries() method
let new_array = T_array.entries();
document.write("<br>The object array iterator values: ");
//using for...of loop
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
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