Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

Array values()

values()方法创建一个新的数组迭代器对象,该对象带有在每个数组索引处指定的值。我们可以通过循环或迭代器方法来迭代数组元素。

语法

array.values();

参数

它不保存任何此类参数。

返回

它创建并返回一个新创建的数组迭代器对象。

JavaScript Array values()方法示例

让我们讨论一些示例以便更好地理解。
Example1
以下是使用for ... of循环实现的示例。
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr = ["John","Mary","Tom","Harry","Sheero"]; //Intializing array elements
var itr = arr.values(); //Using values() method.
document.write("The array elements are:<br>");
for (let x of itr) {
document.write("<br>"+x);
} //This iterates the array elements through its index value.
</script>
</body>
</html>
输出:
迭代之后,数组的元素表示为:
 JavaScript Array values()Method
Example2
使用for的array values()方法的另一种实现。 ..of循环。
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
const arr=["P","Q","R","S","T"]; //Initializing array elements.
const itr=arr.values();
document.write("The array elements are: <br>");
for(let x of itr)
{
document.write("<br>"+x);
} //This loop will iterate and print the array elements.
</script>
</body>
</html>
输出:
输出如下所示:
 JavaScript数组values()方法
Example3
使用next()方法实现的示例。
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr=["John","Tom","Sheero","Romy","Tomy"]; //Initialized array
var itr=arr.values();
document.write("The array elements are: <br>");
document.write("<br>"+itr.next().value);
document.write("<br>"+itr.next().value);
document.write("<br>"+itr.next().value);
document.write("<br>"+itr.next().value);
document.write("<br>"+itr.next().value);
</script>
</body>
</html>
输出:
 JavaScript数组values()方法
注意:如果next()方法的使用超过了给定的数组长度,它将返回一个'undefined'值。
让我们通过一个示例来理解:
示例
<html>
<head> <h5> Javascript Array Methods </h5> </head>
<body>
<script>
var arr=["John","Tom","Sheero","Romy","Tomy"]; //Initialized array
var itr=arr.values();
document.write("The array elements are: <br>");
document.write("<br>"+itr.next().value); //returns value at index 0.
document.write("<br>"+itr.next().value); //returns value at index 1
document.write("<br>"+itr.next().value); //returns value at index 2
document.write("<br>"+itr.next().value); //returns value at index 3
document.write("<br>"+itr.next().value); //returns value at index 4
document.write("<br>"+itr.next().value); //returns undefined
</script>
</body>
</html>
输出:
 JavaScript数组values()方法
很显然,数组的大小为4,即arr [4]。但是next()方法使用了5次。因此,对next()的最后一次调用返回了"未定义"的值。
注意:数组迭代器对象将数组地址作为其值,因此分别取决于数组中存在的值。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4