Arrays
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
An array is one value that holds a list of values, in order. Follow a seven-line script about fruit: make an array with square brackets, read items by their index (counting from 0), ask for its length, change one item, push a new one on the end, find the last item, and visit every item with a for...of loop.
5 أسئلة سريعة
اختر إجابة لتعرف السبب. تُحفَظ نتيجتك مع تقدّمك.
01const pets = ["cat", "dog", "fish"]; What is pets[1]?
Indexes start at 0, so pets[0] is "cat" and pets[1] is the second item, "dog".
02An array holds 5 items. What is the index of the last one?
The last index is always length − 1. With 5 items the indexes are 0, 1, 2, 3 and 4.
03const nums = [10, 20]; nums.push(30); What is nums.length now?
push adds one item at the end, so the length goes from 2 to 3. const only stops the name nums being pointed at a different array; the array itself can still change.
04const fruits = ["apple", "fig"]; What does console.log(fruits[5]) print?
There is no item at index 5, so reading it gives undefined. JavaScript does not stop with an error.
05What does for (const f of ["a", "b", "c"]) console.log(f); print?
for...of visits every item in order. Each time round, f holds the next item, so it prints a, then b, then c.
المسرد
- Array
- One value that holds a list of values, in order. Written with square brackets: ["apple", "pear"].
- Item (element)
- One value stored in an array.
- Index
- The number of an item's place in the array. The first item is at index 0, the next at 1, and so on.
- length
- How many items an array holds. It is always one more than the last index.
- Method
- A function that belongs to a value, called with a dot, such as fruits.push("plum").
- push
- An array method that adds one or more items to the end and returns the new length.
- for...of
- A loop that visits every item of an array in order, putting each one in a variable in turn.
- undefined
- JavaScript's value for "nothing here", for example what you get when you read an index that has no item.
الملاحظات والمصادر
- In JavaScript an array is a kind of object: typeof ["a"] is "object", and Array.isArray() tells arrays apart. fruits holds a reference to the array, which is why const fruits can still have its items changed.
- The slots side by side are a picture of the idea. Engines store arrays in different ways inside, but indexes, length and push always behave as shown.
- Reading an index with no item, such as fruits[9], gives undefined rather than an error. fruits.at(-1) is a newer way to read the last item.
- One array can hold values of any type, even mixed: [1, "two", true] is fine. Most arrays hold one kind of thing, which keeps code simple.
- The script is real. Run it with node fruits.js or paste it into the browser console; it prints apple, 3, plum, apple, kiwi, fig, plum.
اختبار يتاح بعد الخطوة الأخيرة.