Skip to content

数组

学习如何数组存储有序列表的 值, 如何 access 项通过索引, and 如何 循环 over 它们.

你将学到

  • 什么数组是 and 当到 use one
  • 如何 access and 修改项 通过索引
  • 如何 添加 and 移除项 使用推送, pop, shift
  • 如何 循环 over 数组使用 for and forEach

概念讲解

数组

An array is an ordered list of values. Use one whenever you have multiple items of the same kind: a list of names, a set of prices, a sequence of scores. Arrays keep the order and let you refer to each item by its position.

Creating and Accessing

const fruits = ["apple", "banana", "cherry"];
fruits[0];   // "apple"  — indexing starts at 0!
fruits[2];   // "cherry"
fruits.length;  // 3

Indexes start at 0, not 1. This is a convention shared by most languages. The last item is at index length - 1.

Adding and Removing

  • 推送(项) — add to the end.
  • pop() — remove from the end.
  • unshift(项) — add to the front.
  • shift() — remove from the front.
const stack = [1, 2, 3];
stack.push(4);   // [1, 2, 3, 4]
stack.pop();     // 4, stack is now [1, 2, 3]

Looping Over Arrays

The classic pattern uses a for loop with the array's length:

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Modern JavaScript offers cleaner alternatives: fruits.forEach(f => console.log(f)) and fruits.映射(f => f.toUpperCase()). These are methods — functions that belong to the array.

Arrays Are Mutable

Arrays declared with const can still have their *contents* changed (arr.推送(x) works). The const only prevents reassigning the variable to a new array. This is a common source of confusion.

示例代码

              const prices = [10, 25, 15, 30, 8];

// Sum all prices with a for loop:
let total = 0;
for (let i = 0; i < prices.length; i++) {
  total += prices[i];
}
console.log("Total:", total);   // 88

// Find the highest price using a method:
const highest = Math.max(...prices);
console.log("Highest:", highest);  // 30

// Transform with map:
const withTax = prices.map(p => p * 1.2);
console.log("With 20% tax:", withTax);
            

for 循环 accumulates 总计. Math.最大值使用 spread 运算符 (...) 查找最大值. 映射创建新 数组使用每个 price increased 通过 20%.

动手试一试

  • JSON Formatter

    JSON 数组 look 如 [1, 2, 3]. 粘贴数组 and watch formatter pretty-print 每个元素.

常见错误

错误写法

Forgetting 那个数组索引开始 at 0.

正确做法

首先项 是 arr[0], 最后是 arr[arr.长度 - 1]. Off-通过-one 错误是 大多数常见数组 bug — 总是测试边界.

错误写法

Expecting const 到 prevent 更改到 数组's 内容.

正确做法

const locks binding, 不内容. arr.推送(x) still 工作. 到 prevent mutation, use 方法那个返回新 数组 (映射, 筛选) 相反的 mutating ones.

相关代码片段

练习 数组

15 个练习

练习 数组

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误