404 Not Found

404 Not Found


nginx

JavaScript Array Basics

An array is like a row of numbered drawers — each drawer has a number (index) and holds something (data). You can grab items by number, swap them out, or add new ones to the end. Arrays are the data structure you'll use most in everyday development.

What Is an Array

An array is an ordered collection of values that can hold any data type:

HTML
<script>
let arr = [1, 'hello', true, null, undefined];
</script>

A single array can mix different types, but in practice you'll usually store the same type for easier processing.

Creating Arrays

Two ways:

HTML
<script>
// Method 1: Literal syntax (recommended — clean and direct)
let fruits = ['Apple', 'Banana', 'Orange'];

// Method 2: Array constructor
let nums = new Array(1, 2, 3);
let empty = new Array(5);  // Creates an empty array of length 5, NOT [5]!
</script>
⚠️ new Array(5) creates an empty array with length 5, not an array containing the number 5! This trips up many people, so just stick with the [] literal.

Accessing Elements

Array indices start at 0, not 1. The first element is [0], the second is [1], and so on:

HTML
<script>
let fruits = ['Apple', 'Banana', 'Orange'];
fruits[0];   // 'Apple'
fruits[1];   // 'Banana'
fruits[2];   // 'Orange'
</script>

Accessing a non-existent index won't throw an error — it returns undefined:

HTML
<script>
fruits[5];   // undefined
</script>

length Property

length returns the number of elements in the array:

HTML
<script>
let arr = [10, 20, 30];
arr.length;   // 3
</script>

length is always one more than the highest index (since indices start at 0). The last element is at arr.length - 1.

Modifying Elements

Just assign a new value via the index:

HTML
<script>
let fruits = ['Apple', 'Banana', 'Orange'];
fruits[1] = 'Grape';  // Replace 'Banana' with 'Grape'
// ['Apple', 'Grape', 'Orange']
</script>

You can also add elements by index (not recommended — creates empty slots):

HTML
<script>
fruits[5] = 'Watermelon';
// ['Apple', 'Grape', 'Orange', empty × 2, 'Watermelon']
</script>

Example: Basic Array Operations

HTML
<!DOCTYPE html>
<html>
<body>
  <h2>Basic Array Operations</h2>
  <div id="output"></div>
  <script>
    let fruits = ['Apple', 'Banana', 'Orange', 'Grape', 'Watermelon'];
    let html = '<strong>Original array:</strong>' + fruits.join(', ') + '<br>';
    html += '<strong>Length:</strong>' + fruits.length + '<br>';
    html += '<strong>First:</strong>' + fruits[0] + '<br>';
    html += '<strong>Last:</strong>' + fruits[fruits.length - 1] + '<br><br>';

    fruits[1] = 'Mango';
    html += '<strong>After modifying index 1:</strong>' + fruits.join(', ') + '<br>';

    document.getElementById('output').innerHTML = html;
  </script>
</body>
</html>
▶ Try it Yourself

Core Methods

The most commonly used array methods for adding and removing elements:

Method Action Returns
push() Add to end New length
pop() Remove from end Removed element
unshift() Add to beginning New length
shift() Remove from beginning Removed element
HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Array Methods</title></head>
<body>
<pre id="output"></pre>
<script>
let arr = ['a', 'b', 'c'];

arr.push('d');       // ['a','b','c','d']  returns 4
arr.pop();           // ['a','b','c']      returns 'd'
arr.unshift('z');    // ['z','a','b','c']  returns 4
arr.shift();         // ['a','b','c']      returns 'z'

document.getElementById('output').textContent = JSON.stringify(arr);
</script>
</body>
</html>
💡 Memory trick: push/pop work on the tail; unshift/shift work on the head. Methods starting with p affect the end; those starting with s affect the start. un prefixed methods add; without un they remove.

Example: Fruit List Manager

HTML
<!DOCTYPE html>
<html>
<body>
  <h2>Fruit List Manager</h2>
  <input type="text" id="fruitInput" placeholder="Enter a fruit name">
  <button onclick="addFruit()">Add to end</button>
  <button onclick="removeLast()">Remove last</button>
  <p id="output"></p>
  <script>
    let fruits = ['Apple', 'Banana', 'Orange'];

    function showFruits() {
      let html = '<strong>Current fruit list:</strong><br>';
      if (fruits.length === 0) {
        html += '(empty list)';
      } else {
        for (let i = 0; i < fruits.length; i++) {
          html += `[${i}] ${fruits[i]}<br>`;
        }
      }
      html += `<br>Total: ${fruits.length} fruits`;
      document.getElementById('output').innerHTML = html;
    }

    function addFruit() {
      let name = document.getElementById('fruitInput').value.trim();
      if (name) {
        fruits.push(name);
        document.getElementById('fruitInput').value = '';
        showFruits();
      }
    }

    function removeLast() {
      if (fruits.length > 0) {
        let removed = fruits.pop();
        showFruits();
      }
    }

    showFruits();
  </script>
</body>
</html>
▶ Try it Yourself

Checking Arrays: Array.isArray() vs typeof

typeof returns "object" for arrays, which makes it useless for distinguishing arrays from plain objects:

HTML
<script>
let arr = [1, 2, 3];
typeof arr;              // "object"  ← useless!
Array.isArray(arr);      // true      ← correct approach
</script>
⚠️ typeof is unreliable for arrays — always use Array.isArray().

forEach for Iteration

forEach is the most common way to iterate over arrays — more declarative than a for loop:

HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>forEach</title></head>
<body>
<pre id="output"></pre>
<script>
let fruits = ['Apple', 'Banana', 'Orange'];
let result = '';
fruits.forEach(function(fruit, index) {
  result += index + ' ' + fruit + '\n';
});
document.getElementById('output').textContent = result;
</script>
</body>
</html>

Arrow functions make it even more concise:

HTML
<script>
fruits.forEach((fruit, index) => {
  console.log(index, fruit);
});
</script>

Example: forEach in Action

HTML
<!DOCTYPE html>
<html>
<body>
  <h2>forEach Array Iteration</h2>
  <div id="output"></div>
  <script>
    let students = [
      { name: 'Alice', score: 92 },
      { name: 'Bob', score: 85 },
      { name: 'Charlie', score: 78 },
      { name: 'Diana', score: 96 }
    ];

    let html = '<table border="1" cellpadding="8" style="border-collapse:collapse">';
    html += '<tr><th>#</th><th>Name</th><th>Score</th><th>Grade</th></tr>';

    students.forEach((s, i) => {
      let grade = s.score >= 90 ? 'A' : s.score >= 80 ? 'B' : 'C';
      let color = s.score >= 90 ? 'green' : s.score >= 80 ? 'blue' : 'orange';
      html += `<tr>
        <td>${i + 1}</td>
        <td>${s.name}</td>
        <td>${s.score}</td>
        <td style="color:${color}">${grade}</td>
      </tr>`;
    });

    html += '</table>';

    let total = 0;
    students.forEach(s => total += s.score);
    html += `<p>Average: ${(total / students.length).toFixed(1)}</p>`;

    document.getElementById('output').innerHTML = html;
  </script>
</body>
</html>
▶ Try it Yourself
⚠️ Higher-order methods like map, filter, and reduce are even more powerful — covered in the next lesson.


📖 Summary

  1. Create arrays with the [] literal — avoid new Array() (easy to mess up)
  2. Indices start at 0; the last element is at index length - 1
  3. push/pop work on the tail; unshift/shift work on the head
  4. Use Array.isArray() to check if something is an array — typeof returns "object" and is unreliable
  5. forEach is more declarative than for, but you can't use break to exit early

❓ FAQ

Q What do push and unshift return?
A Both return the array's new length, not the modified array. Many people expect the array itself — let arr = [1].push(2) gives you 2 (the length), not [1, 2].
Q Can I use break inside forEach?
A No. forEach has no break mechanism. To exit early, use a traditional for loop or for...of with break.
Q Does accessing an out-of-bounds index throw an error?
A No. arr[100] returns undefined when out of bounds — no exception is thrown. But this can hide bugs, so it's good practice to check the index range before accessing.

📝 Exercises

  1. Create an array of 5 city names and use forEach to display each city's number and name on the page
  2. Build a to-do list: input tasks to add to the end, click "Done" to remove the last task, and display the list in real time
  3. Write a program that takes 5 numbers as input, stores them in an array, and displays their sum and average
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏