Arrays · المصفوفات
Arrays hold lists
- An array is an ordered list of values in
[ ... ]. - Reach an item by its index, counting from
0:arr[0]is the first. .lengthtells you how many items there are.
المصفوفات تحتفظ بالقوائم
- المصفوفة هي قائمة مرتبة من القيم في
[ ... ]. - تصل إلى عنصر عن طريق الفهرس، بدءاً من
0:arr[0]هو الأول. .lengthيخبرك بعدد العناصر.
let nums = [10, 20, 30];
console.log(nums[0]); // → 10
console.log(nums.length); // → 3
Add and remove items
.push(x)addsxto the end;.pop()removes the last item.- The array grows and shrinks as you go.
إضافة وإزالة عناصر
.push(x)يضيفxإلى النهاية؛.pop()يزيل العنصر الأخير.- تنمو المصفوفة وتضيق كلما تقدمت.
let nums = [10, 20, 30];
nums.push(40);
console.log(nums); // → [10,20,30,40]
nums.pop();
console.log(nums); // → [10,20,30]
Index, push and pop · الفهرس، push و pop
Items are numbered from 0. push adds to the end; pop removes from the end. · العناصر مرقّمة بدءاً من 0. push تُضيف في النهاية؛ pop تُزيل من النهاية.
Loop over an array
- A
forloop with an index visits each item, from0tolength - 1.
المرور على مصفوفة
- حلقة
forبفهرس تزور كل عنصر، من0إلىlength - 1.
let nums = [1, 2, 3];
for (let i = 0; i < nums.length; i++) {
console.log(nums[i]); // → 1, then 2, then 3
}
Common mistakes
- Index from
0;a.lengthis the size. pushadds to the end;popremoves from the end.
أخطاء شائعة
- الفهرس يبدأ من
0؛a.lengthهو الحجم. pushيضيف إلى النهاية؛popيزيل من النهاية.
Now you try
- Use an index, or a loop, on each array.
- Press Check answer to test it.
الآن جرب بنفسك
- استخدم فهارس أو حلقات على كل مصفوفة.
- اضغط على تحقق من الإجابة لاختبارها.
let colours = ["red", "green", "blue"]. Log the second item, colours[1] (it is green). · let colours = ["red", "green", "blue"]. أخرج العنصر الثاني، colours[1] (وهو green).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
let nums = [4, 8, 15, 16]. Log how many items it has with .length (it is 4). · let nums = [4, 8, 15, 16]. أخرج عدد عناصرها باستخدام .length (وهو 4).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
let stack = [1, 2]. Use .push to add 3, then log the array (it is [1,2,3]). · let stack = [1, 2]. استخدم .push لإضافة 3، ثم أخرج المصفوفة (وهي [1,2,3]).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Use a for loop to add up every number in nums and log the total (it is 43). · استخدم حلقة for لجمع كل رقم في nums وأخرج المجموع (وهو 43).
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.