Node.js – forEach() 方法
Node.js 中的 forEach() 方法用于遍历一组给定的数组项。可以使用 forEach 数组循环逐个迭代数组的所有值。
语法
arrayName.forEach(function)
参数
- 函数 − 该函数接受将被执行的方法的输入。
- 数组名称 − 将被迭代的数组。
示例 1
创建一个文件 "forEach.js",复制以下代码段。创建文件后,使用命令 "node forEach.js" 运行此代码。
// forEach() Demo Example
// Defining a vehicle array
const vehicleArray = ['bike', 'car', 'bus'];
// Iterating over the array and printing
vehicleArray.forEach(element => {
console.log(element);
});结果
C:\home
ode>> node forEach.js bike car bus
示例 2
// forEach() Demo Example
// Defining a vehicle array
const array = [1,2,3,4,5,6,7,8,9];
var sum=0;
// Iterating over the array and printing
array.forEach(element => {
sum += element;
});
console.log(sum);结果
C:\home
ode>> node forEach.js 45
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP