溫馨提示×

如何使用each遍歷數(shù)組元素

PHP
小樊
81
2024-09-21 01:20:41
欄目: 編程語言

在JavaScript中,可以使用forEach方法遍歷數(shù)組元素。以下是一個示例:

const arr = ['apple', 'banana', 'cherry'];

arr.forEach(function(element, index, array) {
  console.log('Element at index ' + index + ' is: ' + element);
});

或者使用箭頭函數(shù)簡化代碼:

const arr = ['apple', 'banana', 'cherry'];

arr.forEach((element, index, array) => {
  console.log('Element at index ' + index + ' is: ' + element);
});

在這個示例中,forEach方法接受一個回調(diào)函數(shù)作為參數(shù)?;卣{(diào)函數(shù)又接受三個參數(shù):當(dāng)前元素(element)、當(dāng)前元素的索引(index)和原數(shù)組(array)。在回調(diào)函數(shù)中,我們可以對每個數(shù)組元素執(zhí)行所需的操作。

0