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