JavaScript迭代器函数的使用


本文将讨论JavaScript中迭代器函数的重要性。我们可以使用迭代器函数来迭代数组。除了显式迭代之外,JavaScript还提供各种迭代函数,可用于迭代数组。这里,我们使用forEach()、filter()方法和map()方法来迭代数组并执行所需的操作。

ForEach函数

此函数将一个函数作为参数,并在数组中的每个对象上执行该函数。

语法

以下是forEach()方法的语法。

array.forEach(function(currentValue, index, arr), thisValue)

示例1

一个使用forEach()方法作为JavaScript中迭代器函数的示例

let people = ['Harry', 'Martha', 'John', 'Sam']
people.forEach(person => console.log(person.toUpperCase()));

示例2

在这个例子中,我们将讨论forEach()方法的使用。在这里,我们使用forEach()方法迭代数组并显示结果。

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Iterator functions in JavaScript</title>
      <div id="forEach"></div>
   </head>
   <body>
      <script type="text/javascript">
         let students = ["Harry", "Martha", "John", "Sam"];
         students.forEach((mem) => document.write(mem.toUpperCase(), "<br>"));
      </script>
   </body>
</html>

Filter()函数

此函数对数组中的每个对象执行传递给它的函数,并根据返回真值的值创建一个新数组。

语法

以下是filter()方法的语法。

array.filter(function(currentValue, index, arr), thisValue)

示例1

在这个例子中,我们将讨论filter()方法的使用。我们使用filter()方法迭代数组并显示结果。

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Iterator functions in JavaScript</title>
   </head>
   <body>
      <script type="text/javascript">
         let students = ["Harry", "Martha", "John", "Sam"];
         document.write(students.filter((mem) => mem[0] === "H"));
      </script>
  </body>
</html>

示例2

另一个使用filter()函数的迭代示例如下:

let people = ['Harry', 'Martha', 'John', 'Sam']
console.log(people.filter(person => person[0] === 'H'));

Map函数

此函数对数组中的每个对象执行传递给它的函数,并根据返回的值创建一个新数组。

语法

以下是map()方法的语法。

array.map(function(currentValue, index, arr), thisValue)

示例1

在这个例子中,我们将讨论map()方法的使用。在这里,我们使用map()方法迭代数组并显示结果。

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Iterator functions in JavaScript</title>
      <div id="map"></div>
   </head>
   <body>
      <script type="text/javascript">
         let students = ["Harry", "Martha", "John", "Sam"];
         let upperCaseNames = students.map((mem) => mem.toUpperCase());
         document.getElementById("map").innerHTML = upperCaseNames;
      </script>
   </body>
</html>

示例2

以下示例使用map()函数在JavaScript中执行迭代:

let people = ['Harry', 'Martha', 'John', 'Sam']
let upperCaseNames = people.map(person => person.toUpperCase())
console.log(upperCaseNames);

更新于:2022年12月16日

259 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.