for loops · לולאות for
Repeating with a for loop
- A loop runs the same block many times, so you don't repeat yourself.
for (let i = 1; i <= 5; i++) { ... }has three parts: starti = 1, testi <= 5, stepi++.
חזרה באמצעות לולאת for
- לולאה מבצעת אותו בלוק מספר פעמים רבות, כך שאין צורך לחזור על עצמך.
- ל
for (let i = 1; i <= 5; i++) { ... }יש שלושה חלקים: התחלהi = 1, בדיקהi <= 5, צעדi++.
for (let i = 1; i <= 3; i++) {
console.log(i); // → 1, then 2, then 3
}
Build a running total
- Keep a variable outside the loop and add to it on every pass.
בניית סכום מצטבר
- שמור משתנה מחוץ ללולאה והוסף אליו בכל עובר.
let total = 0;
for (let i = 1; i <= 10; i++) {
total = total + i;
}
console.log(total); // → 55
Trace the running total · עקוב אחר הסכום הנערך
A loop repeats its body. Step through the passes and watch total grow. · לולאה חוזרת על גופה. עבור על העברות והצפה כיצד total גדל.
Watch out
i <= 5stops after 5;i < 5stops before 5. Picking the wrong one is the classic "off-by-one" bug.- Start the total at
0before the loop, not inside it.
שימו לב
- ל
i <= 5נעצר אחרי 5; לi < 5נעצר לפני 5. בחירת הלא נכון היא הבאג הקלאסי "שגיאת סטייה מאחד" (off-by-one). - התחל את הסכום ב-
0לפני הלולאה, לא בתוכה.
Common mistakes
for (let i = 0; i < n; i++)runsntimes.- Declare the counter with
let, not without.
טעויות נפוצות
- ל
for (let i = 0; i < n; i++)פועלתnפעמים. - הכרז את המונה עם
let, לא בלי.
Now you try
- Use a
forloop. - Press Check answer to test it.
כעת תנסו בעצמכם
- השתמש בלולאת
for. - לחץ על בדיקת תשובה כדי לבדוק אותה.
Use a for loop to log the numbers 1 to 5, one per line. · השתמש בלולאת for כדי להדפיס את המספרים 1 עד 5, אחד בשורה.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Use a for loop to add up 1 to 10, then log the total (it is 55). · השתמש בלולאת for כדי לסכום את 1 עד 10, ואז הדפס את הסך הכל (זהו 55).
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Use a for loop to log the even numbers 2, 4, 6, one per line (step by 2 with i += 2). · השתמש בלולאת for כדי להדפיס את המספרים הזוגיים 2, 4, 6, אחד בשורה (צעד ב-2 עם i += 2).
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.