JavaScript TypedArray values() 方法返回一个数组迭代器对象,该对象迭代类型化数组中每个元素的值。此特定方法不适用于所有数组,只能在类型化数组的实例上调用。
语法
以下是 JavaScript TypedArray values() 方法的语法 -
values()
参数
它不接受任何参数。
返回值
此方法返回一个新的数组可迭代对象。
示例 1
下面的程序演示了 JavaScript TypedArray values() 方法的用法。
<html>
<head>
<title>JavaScript TypedArray values() 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 values() method
let new_array = T_array.values();
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 values() 方法的另一个示例。使用此方法,我们尝试从此类型化数组 [10, 20, 30, 40, 50] 中检索新的对象数组迭代器。我们在对象数组迭代器上使用 next().value 来检索特定元素。
<html>
<head>
<title>JavaScript TypedArray values() 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 values() method
let new_array = T_array.values();
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>
输出
执行上述程序后,它返回以下输出 -
The original typed array: 10,20,30,40,50
The new_array iterator object: [object Array Iterator]
The new_array.next().value returns: 10
The new_array iterator object: [object Array Iterator]
The new_array.next().value returns: 10
示例 3
在此示例中,我们使用 for...of 循环遍历 values() 方法返回的对象数组迭代器的每个元素。
<html>
<head>
<title>JavaScript TypedArray values() 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 values() method
let new_array = T_array.values();
document.write("<br>The object array iterator values: ");
//using for...of loop
for(const i of new_array){
document.write(i, " ");
}
</script>
</body>
</html>
输出
执行上述程序后,它将对象数组迭代器的每个元素返回为 -
The original typed array: 10,20,30,40,50
The object array iterator values: 10 20 30 40 50
The object array iterator values: 10 20 30 40 50