Skip to content

for

ใช้สำหรับวนซ้ำตามช่วงที่กำหนดในลูป

javascript
const limit = 5;
for (let index = 0; index < limit; index++) {
    console.log(index); // Output: 0 1 2 3 4
}

for...in

ใช้สำหรับวนซ้ำผ่าน property ของ object

javascript
const person = {name: 'John', age: 30, job: 'developer'};
for (let key in person) {
    console.log(key + ': ' + person[key]); 
    // Output: name: John
    //         age: 30
    //         job: developer
}

for...of

ใช้สำหรับวนซ้ำผ่านค่าใน iterable objects เช่น arrays

javascript
const fruits = ['apple', 'banana', 'orange'];
for (let fruit of fruits) {
    console.log(fruit); 
    // Output: apple
    //         banana
    //         orange
}

while

ทำซ้ำตราบใดที่เงื่อนไขยังเป็นจริง

javascript
let count = 0;
while (count < 5) {
    console.log(count); 
    // Output: 0 1 2 3 4
    count++;
}

do...while

ทำซ้ำอย่างน้อยหนึ่งครั้ง แล้วตรวจสอบเงื่อนไข

javascript
let x = 0;
do {
    console.log(x); 
    // Output: 0 1 2 3 4
    x++;
} while (x < 5);

array

array forEach

method ของ array ที่ใช้เพื่อทำงานกับแต่ละสมาชิกของ array

javascript
const fruits = ['apple', 'banana', 'orange'];
fruits.forEach(fruit => {
    console.log(fruit); 
    // Output: apple
    //         banana
    //         orange
});

array map

สร้าง array ใหม่โดยใช้ฟังก์ชันกับทุกสมาชิกของ array เดิม

javascript
const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map(num => num * num);
console.log(squared); 
// Output: [1, 4, 9, 16, 25]

array reduce

ลดค่าของ array ให้เหลือค่าเดียวโดยใช้ฟังก์ชัน

javascript
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
console.log(sum); 
// Output: 15

Released under the MIT License