JavaScript Array forEach()
ตัวอย่าง 1
เรียกใช้ฟังก์ชันสำหรับแต่ละองค์ประกอบในผลไม้:
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
ความหมายและการใช้งาน
วิธี การforEach()
เรียกใช้ฟังก์ชันสำหรับแต่ละองค์ประกอบในอาร์เรย์
วิธี การforEach()
นี้ไม่ได้ดำเนินการสำหรับองค์ประกอบที่ว่างเปล่า
ไวยากรณ์
array.forEach(function(currentValue, index, arr), thisValue)
พารามิเตอร์
function() | Required. A function to run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
คืนมูลค่า
ไม่ได้กำหนด |
รองรับเบราว์เซอร์
forEach()
เป็นคุณลักษณะ ECMAScript5 (ES5)
ES5 (JavaScript 2009) รองรับทุกเบราว์เซอร์:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
ตัวอย่างเพิ่มเติม
คำนวณผลรวม:
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
คูณแต่ละองค์ประกอบ:
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function
myFunction(item, index, arr) {
arr[index] = item * 10;
}