រង្វិល (Loops)
សេចក្តីផ្តើម
Loops គឺជាវិធីសាស្រ្តសំខាន់ក្នុង JavaScript សម្រាប់បញ្ជូនកូដម្តងហើយម្តងទៀត។ វាអាចប្រើសម្រាប់បញ្ជូនកូដលើ array, object, ឬចំនួនកំណត់។
ប្រភេទ Loops
Loop | Syntax | Use Case |
---|---|---|
for | for (init; condition; update) { ... } | ច្បាស់លាស់, ចំនួនកំណត់ |
while | while (condition) { ... } | បន្តរហូតដល់លក្ខខណ្ឌមិនពិត |
do...while | do { ... } while (condition) | បញ្ជូនកូដយ៉ាងហោចណាស់ម្តង |
for...in | for (key in object) { ... } | loop លើ object properties |
for...of | for (item of iterable) { ... } | loop លើ array, string, iterable |
for Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
Loop ចាប់ពី 0 ដល់ 4
while Loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Loop រហូតដល់ i >= 5
do...while Loop
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
បញ្ជូនកូដយ៉ាងហោចណាស់ម្តង
for...in Loop
const obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
console.log(key, obj[key]);
}
Loop លើ properties នៃ object
for...of Loop
const arr = [10, 20, 30];
for (let value of arr) {
console.log(value);
}
Loop លើ array, string, iterable
Break & Continue
for (let i = 0; i < 10; i++) {
if (i === 5) break; // បញ្ឈប់ loop
if (i % 2 === 0) continue; // រំលង
console.log(i);
}
break
បញ្ឈប់ loop, continue
រំលង iteration
Best Practices
- ប្រើ
for...of
សម្រាប់ array - ប្រើ
for...in
សម្រាប់ object - ប្រើ
break
និងcontinue
ដោយប្រុងប្រយ័ត្ន - ជៀសវាង infinite loops
- ប្រើ
Array.forEach()
សម្រាប់ callback
Interactive Examples
- Loop Counter
- Sum Array
- Object Properties Viewer
- String Character Loop
- Break/Continue Demo
សង្ខេប
- Loops អាចបញ្ជូនកូដម្តងហើយម្តងទៀត
- ប្រភេទ loops: for, while, do...while, for...in, for...of
- break/continue សម្រាប់គ្រប់គ្រង loop
- ប្រើ loops ដោយប្រុងប្រយ័ត្ន