Skip to content

10. 数组(批量存储数据)

数组是 JavaScript 中用于批量存储数据的数据结构。本章节将带你学习 JavaScript 数组的定义、创建、元素的获取与修改,以及常用的数组方法。

10.1 数组的定义与创建

数组是一种有序的集合,可以存储任意类型的数据。

数组的创建

1. 使用数组字面量

javascript
// 创建空数组
const emptyArray = [];

// 创建包含元素的数组
const numbers = [1, 2, 3, 4, 5];
const fruits = ['apple', 'banana', 'cherry'];
const mixed = [1, 'apple', true, null, undefined, { name: 'John' }, [1, 2, 3]];

2. 使用 Array 构造函数

javascript
// 创建空数组
const emptyArray = new Array();

// 创建指定长度的数组
const arrayWithLength = new Array(5);

// 创建包含元素的数组
const numbers = new Array(1, 2, 3, 4, 5);
const fruits = new Array('apple', 'banana', 'cherry');

3. 使用 Array.from()

javascript
// 从类数组对象创建数组
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
const array1 = Array.from(arrayLike);  // ['a', 'b', 'c']

// 从可迭代对象创建数组
const set = new Set(['a', 'b', 'c']);
const array2 = Array.from(set);  // ['a', 'b', 'c']

// 使用映射函数
const array3 = Array.from([1, 2, 3], x => x * 2);  // [2, 4, 6]

4. 使用 Array.of()

javascript
// 创建包含元素的数组
const numbers = Array.of(1, 2, 3, 4, 5);  // [1, 2, 3, 4, 5]
const fruits = Array.of('apple', 'banana', 'cherry');  // ['apple', 'banana', 'cherry']

10.2 数组元素的获取与修改

访问数组元素

使用索引访问数组元素,索引从 0 开始:

javascript
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits[0]);  // 'apple'
console.log(fruits[1]);  // 'banana'
console.log(fruits[2]);  // 'cherry'
console.log(fruits[3]);  // undefined(索引超出范围)

修改数组元素

javascript
const fruits = ['apple', 'banana', 'cherry'];
fruits[1] = 'orange';  // 修改第二个元素
console.log(fruits);  // ['apple', 'orange', 'cherry']

fruits[3] = 'grape';  // 添加新元素
console.log(fruits);  // ['apple', 'orange', 'cherry', 'grape']

数组长度

使用 length 属性获取或设置数组的长度:

javascript
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.length);  // 3

// 修改数组长度
fruits.length = 2;
console.log(fruits);  // ['apple', 'banana']

fruits.length = 5;
console.log(fruits);  // ['apple', 'banana', undefined, undefined, undefined]

10.3 数组常用方法(新手必学)

增:push() unshift()

push() 方法

在数组末尾添加一个或多个元素,返回新的数组长度:

javascript
const fruits = ['apple', 'banana'];
const length = fruits.push('cherry', 'orange');
console.log(fruits);  // ['apple', 'banana', 'cherry', 'orange']
console.log(length);  // 4

unshift() 方法

在数组开头添加一个或多个元素,返回新的数组长度:

javascript
const fruits = ['banana', 'cherry'];
const length = fruits.unshift('apple', 'orange');
console.log(fruits);  // ['apple', 'orange', 'banana', 'cherry']
console.log(length);  // 4

删:pop() shift() splice()

pop() 方法

移除并返回数组的最后一个元素:

javascript
const fruits = ['apple', 'banana', 'cherry'];
const lastFruit = fruits.pop();
console.log(lastFruit);  // 'cherry'
console.log(fruits);  // ['apple', 'banana']

shift() 方法

移除并返回数组的第一个元素:

javascript
const fruits = ['apple', 'banana', 'cherry'];
const firstFruit = fruits.shift();
console.log(firstFruit);  // 'apple'
console.log(fruits);  // ['banana', 'cherry']

splice() 方法

修改数组,添加或删除元素:

javascript
const fruits = ['apple', 'banana', 'cherry', 'orange'];

// 删除元素
const removed = fruits.splice(1, 2);  // 从索引 1 开始删除 2 个元素
console.log(removed);  // ['banana', 'cherry']
console.log(fruits);  // ['apple', 'orange']

// 添加元素
fruits.splice(1, 0, 'banana', 'cherry');  // 从索引 1 开始添加元素
console.log(fruits);  // ['apple', 'banana', 'cherry', 'orange']

// 替换元素
fruits.splice(2, 1, 'grape');  // 从索引 2 开始删除 1 个元素并添加新元素
console.log(fruits);  // ['apple', 'banana', 'grape', 'orange']

查:indexOf() includes()

indexOf() 方法

返回元素在数组中首次出现的索引,未找到返回 -1:

javascript
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.indexOf('banana'));  // 1
console.log(fruits.indexOf('orange'));  // -1

includes() 方法

检查数组是否包含指定元素,返回布尔值:

javascript
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.includes('banana'));  // true
console.log(fruits.includes('orange'));  // false

遍历:for 循环遍历数组

javascript
const fruits = ['apple', 'banana', 'cherry'];

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

// for...of 循环
for (const fruit of fruits) {
    console.log(fruit);
}

// forEach() 方法
fruits.forEach((fruit, index) => {
    console.log(index, fruit);
});

10.4 实战:数组排序 / 筛选数据 / 统计元素

实战1:数组排序

javascript
// 数字排序
const numbers = [5, 2, 8, 1, 4];

// 升序排序
numbers.sort((a, b) => a - b);
console.log(numbers);  // [1, 2, 4, 5, 8]

// 降序排序
numbers.sort((a, b) => b - a);
console.log(numbers);  // [8, 5, 4, 2, 1]

// 字符串排序
const fruits = ['cherry', 'apple', 'banana'];
fruits.sort();
console.log(fruits);  // ['apple', 'banana', 'cherry']

// 对象排序
const people = [
    { name: 'John', age: 30 },
    { name: 'Jane', age: 25 },
    { name: 'Bob', age: 35 }
];

// 按年龄排序
people.sort((a, b) => a.age - b.age);
console.log(people);

实战2:筛选数据

javascript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// 筛选偶数
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log('偶数:', evenNumbers);  // [2, 4, 6, 8, 10]

// 筛选大于 5 的数
const greaterThan5 = numbers.filter(num => num > 5);
console.log('大于 5 的数:', greaterThan5);  // [6, 7, 8, 9, 10]

// 筛选对象
const people = [
    { name: 'John', age: 30, gender: 'male' },
    { name: 'Jane', age: 25, gender: 'female' },
    { name: 'Bob', age: 35, gender: 'male' }
];

// 筛选男性
const males = people.filter(person => person.gender === 'male');
console.log('男性:', males);

// 筛选年龄大于 28 的人
const olderThan28 = people.filter(person => person.age > 28);
console.log('年龄大于 28 的人:', olderThan28);

实战3:统计元素

javascript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// 计算总和
const sum = numbers.reduce((total, num) => total + num, 0);
console.log('总和:', sum);  // 55

// 计算平均值
const average = sum / numbers.length;
console.log('平均值:', average);  // 5.5

// 统计偶数的个数
const evenCount = numbers.filter(num => num % 2 === 0).length;
console.log('偶数的个数:', evenCount);  // 5

// 统计出现次数
const fruits = ['apple', 'banana', 'cherry', 'apple', 'banana', 'apple'];
const count = {};
fruits.forEach(fruit => {
    count[fruit] = (count[fruit] || 0) + 1;
});
console.log('出现次数:', count);  // { apple: 3, banana: 2, cherry: 1 }

小结

通过本章节的学习,你已经掌握了:

  • 数组的定义与创建
  • 数组元素的获取与修改
  • 数组的常用方法:
    • 增加元素:push()、unshift()
    • 删除元素:pop()、shift()、splice()
    • 查找元素:indexOf()、includes()
    • 遍历元素:for 循环、for...of 循环、forEach()
  • 如何使用数组解决实际问题:排序、筛选数据、统计元素

在后续的章节中,我们将学习 JavaScript 的对象和字符串常用方法。

© 2026 编程马·菜鸟教程 版权所有