Level: Intermediate | Player: 06_Object
Learning Objectives
- You can create an array and use Access/Modify as the index.
- Understand the meaning and operation of
length. - Elements can be Add/Delete as
push,pop,shift, andunshift. - Know the difference between
spliceandslice(whether the original has been changed or not). - Iterate through the array with
for...of.
1. Array creation and index
An array is an ordered collection of values, accessed by index starting from 0.
const fruits = ["apple", "banana", "grapes"];
console.log(fruits[0]); //"apple"
console.log(fruits.length); // 3
fruits[1] = "strawberry";
length is the largest index + 1. If you shorten it like fruits.length = 1, the rear elements will be cut off.
2. Adding and removing end/front
push/pop operates at the end, and unshift/shift operates at the front. Forward operations are slower because they move all elements.
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
arr.unshift(0); // [0, 1, 2, 3]
arr.shift(); // [1, 2, 3]
3. splice and slice
splice(start, deleteCount, ...items) changes the original, and slice(start, end) returns a new array (without end).
const nums = [1, 2, 3, 4, 5];
const removed = nums.splice(1, 2, 99); // nums = [1, 99, 4, 5], removed = [2,3]
const copy = nums.slice(1, 3); //[99, 4] As original
4. Traversal (for...of)
If you don't need an index, for...of is the most concise. If you also need an index, use entries().
for (const item of fruits) console.log(item);
for (const [i, item] of fruits.entries()) console.log(i, item);
Core example
| file | Contents covered |
|---|---|
01_index.js |
Index access, length operation |
02_push_pop.js |
Add/Delete method |
03_splice.js |
splice vs slice |
04_iteration.js |
for, for...of, forEach |
⚠️ Common Mistakes
- Reading an index that does not exist and calling a method on
undefinedcauses a TypeError. - Apply it twice, forgetting that
splicechanges the original. - Try to compare the array with
===(reference comparison). - Create an empty slot using
delete arr[1]— usesplice. - When copying an object or array, it is not recognized as a shallow copy.
❓ Frequently Asked Questions (FAQ)
Q1. Are arrays also objects? A. Yes. typeof [] is "object", and to determine it accurately, use Array.isArray().
Q2. What about checking for empty arrays? A. arr.length === 0 is safe.
Q3. How to copy an array? A. arr.slice(), [...arr], and Array.from(arr) all make shallow copies.