在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í)行所需的操作。