Putting it together · שילוב הכל יחד
Putting it together
- Real programs combine variables, loops, functions, arrays and objects.
- A
for...ofloop reads each item of an array directly — no index needed.
חיבור הכל יחד
- תוכניות אמיתיות משלבות משתנים, לולאות, פונקציות, מערכים ואובייקטים.
- לולאת
for...ofקוראת כל פריט במערך ישירות — אין צורך במקדם.
function total(nums) {
let t = 0;
for (const n of nums) {
t = t + n;
}
return t;
}
console.log(total([4, 8, 6])); // → 18
for...of builds the total · for...of בונה את הסכום
for...of reads each item directly. Watch t add them up, one at a time. · for...of קורא כל פריט ישירות. השים לב כיצד t מוסיף אותם אחד אחד.
Searching and counting
- Loop through the array, and keep a counter (or a flag) as you go.
חיפוש וספירה
- עבור על המערך, ושמור על מדד (או סימן) בזמן התהליך.
function countAbove(nums, limit) {
let count = 0;
for (const n of nums) {
if (n > limit) {
count++;
}
}
return count;
}
console.log(countAbove([3, 7, 2, 8], 4)); // → 2
Common mistakes
- Build in small steps and use
console.logto check as you go. - Keep the HTML, CSS and JavaScript doing their own jobs.
טעויות נפוצות
- בנה בשלבים קטנים והשתמש ב
console.logכדי לבדוק כשאתה הולך. - שמור על כך ש-HTML, CSS ו-Javascript יעשו את העבודה שלהם כל אחד בעצמו.
Now you try
- Write each function using a loop.
- Press Check answer to test it.
כעת תנסו בעצמכם
- כתוב כל פונקציה באמצעות לולאה.
- לחץ על בדיקת תשובה כדי לבדוק אותה.
Write a function total(nums) that returns the sum of every number in the array nums. · כתוב פונקציית total(nums) שמחזירה את סכום כל המספרים במערכת nums.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Write a function biggest(nums) that returns the largest value in the array. · כתוב פונקציית biggest(nums) שמחזירה את הערך הגדול ביותר במערכת.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Write a function countAbove(nums, limit) that returns how many numbers are greater than limit. · כתוב פונקציית countAbove(nums, limit) שמחזירה כמה מספרים הם גדולים מlimit.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.