数组创建与访问
2025年3月7日大约 6 分钟
数组创建与访问
JavaScript数组是用于存储多个值的特殊对象。本文将介绍创建数组的多种方式、访问数组元素的语法以及数组的基本特性。
数组的基本概念
数组是一种线性数据结构,用于按顺序存储元素的集合。在JavaScript中,数组是一种特殊的对象,具有以下特点:
- 可以存储任意类型的数据(数字、字符串、对象、函数等)
- 数组长度是动态的,可以随时调整
- 数组索引从0开始
- 数组元素可以通过索引直接访问
创建数组
JavaScript提供了多种创建数组的方法:
1. 数组字面量
最常用的创建数组方式是使用方括号 []
表示的数组字面量:
// 空数组
const emptyArray = [];
// 包含元素的数组
const fruits = ['苹果', '香蕉', '橙子'];
// 不同类型的元素
const mixed = [1, 'hello', true, { name: 'John' }, [1, 2, 3]];
2. Array构造函数
可以使用 Array
构造函数创建数组:
// 创建空数组
const arr1 = new Array();
// 创建指定长度的数组(所有元素为undefined)
const arr2 = new Array(5);
console.log(arr2.length); // 5
console.log(arr2); // [empty × 5]
// 创建包含指定元素的数组
const arr3 = new Array('苹果', '香蕉', '橙子');
注意
当 Array
构造函数只接收一个数值参数时,它会创建一个长度为该数值的空数组,而不是包含该数值的数组。
const arr4 = new Array(3); // 创建长度为3的空数组: [empty × 3]
const arr5 = new Array('3'); // 创建包含字符串"3"的数组: ["3"]
3. Array.of() 方法
ES6引入的 Array.of()
方法创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型:
// 创建包含单个数字的数组
const arr6 = Array.of(5);
console.log(arr6); // [5]
// 创建包含多个元素的数组
const arr7 = Array.of(1, 'hello', true);
console.log(arr7); // [1, "hello", true]
4. Array.from() 方法
ES6引入的 Array.from()
方法从类数组对象或可迭代对象创建一个新的数组实例:
// 从字符串创建数组
const arr8 = Array.from('hello');
console.log(arr8); // ["h", "e", "l", "l", "o"]
// 从Set创建数组
const set = new Set([1, 2, 3, 2, 1]);
const arr9 = Array.from(set);
console.log(arr9); // [1, 2, 3]
// 使用映射函数
const arr10 = Array.from([1, 2, 3], x => x * 2);
console.log(arr10); // [2, 4, 6]
5. 扩展运算符
ES6的扩展运算符 ...
也可以用来创建新数组:
// 复制数组
const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // [1, 2, 3]
// 合并数组
const arr11 = [1, 2, 3];
const arr12 = [4, 5, 6];
const merged = [...arr11, ...arr12];
console.log(merged); // [1, 2, 3, 4, 5, 6]
访问数组元素
1. 使用索引访问
数组元素可以通过索引(从0开始的整数)访问:
const fruits = ['苹果', '香蕉', '橙子', '草莓'];
// 访问第一个元素
console.log(fruits[0]); // "苹果"
// 访问第三个元素
console.log(fruits[2]); // "橙子"
// 访问最后一个元素
console.log(fruits[fruits.length - 1]); // "草莓"
2. 使用at()方法
ES2022引入的 at()
方法接收一个整数值并返回该索引处的元素,允许负索引:
const fruits = ['苹果', '香蕉', '橙子', '草莓'];
// 访问第一个元素
console.log(fruits.at(0)); // "苹果"
// 访问最后一个元素
console.log(fruits.at(-1)); // "草莓"
// 访问倒数第二个元素
console.log(fruits.at(-2)); // "橙子"
3. 修改数组元素
可以通过索引直接修改数组元素:
const fruits = ['苹果', '香蕉', '橙子'];
// 修改第二个元素
fruits[1] = '葡萄';
console.log(fruits); // ["苹果", "葡萄", "橙子"]
// 添加新元素
fruits[3] = '芒果';
console.log(fruits); // ["苹果", "葡萄", "橙子", "芒果"]
// 创建稀疏数组(不推荐)
fruits[6] = '西瓜';
console.log(fruits); // ["苹果", "葡萄", "橙子", "芒果", empty × 2, "西瓜"]
console.log(fruits.length); // 7
4. 遍历数组元素
有多种方法可以遍历数组元素:
const fruits = ['苹果', '香蕉', '橙子'];
// 使用for循环
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// 使用for...of循环(ES6)
for (const fruit of fruits) {
console.log(fruit);
}
// 使用forEach方法
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
数组的基本属性和方法
1. length属性
length
属性返回或设置数组中元素的数量:
const fruits = ['苹果', '香蕉', '橙子'];
console.log(fruits.length); // 3
// 通过设置length属性可以截断数组
fruits.length = 2;
console.log(fruits); // ["苹果", "香蕉"]
// 增加length不会创建新元素
fruits.length = 5;
console.log(fruits); // ["苹果", "香蕉", empty × 3]
2. 检查数组
检查一个变量是否为数组:
const fruits = ['苹果', '香蕉', '橙子'];
// 使用Array.isArray()方法(推荐)
console.log(Array.isArray(fruits)); // true
console.log(Array.isArray({})); // false
// 使用instanceof运算符
console.log(fruits instanceof Array); // true
3. 转换为字符串
将数组转换为字符串:
const fruits = ['苹果', '香蕉', '橙子'];
// 使用toString()方法
console.log(fruits.toString()); // "苹果,香蕉,橙子"
// 使用join()方法指定分隔符
console.log(fruits.join()); // "苹果,香蕉,橙子"
console.log(fruits.join(' - ')); // "苹果 - 香蕉 - 橙子"
console.log(fruits.join('')); // "苹果香蕉橙子"
多维数组
JavaScript支持多维数组,即数组的元素也是数组:
// 创建二维数组
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// 访问元素
console.log(matrix[1][2]); // 6
// 遍历二维数组
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}
类数组对象
JavaScript中有一些对象看起来像数组,但实际上不是数组,称为"类数组对象"。例如:
- 函数中的
arguments
对象 - DOM方法返回的
NodeList
对象 - 字符串
类数组对象有索引和length属性,但不具有数组的方法(如push、pop等)。可以使用 Array.from()
将类数组对象转换为真正的数组:
function example() {
// arguments是类数组对象
console.log(Array.isArray(arguments)); // false
// 转换为真正的数组
const args = Array.from(arguments);
console.log(Array.isArray(args)); // true
// 现在可以使用数组方法
return args.map(x => x * 2);
}
console.log(example(1, 2, 3)); // [2, 4, 6]
数组的性能考虑
- 访问数组元素的时间复杂度为O(1)
- 在数组开头添加/删除元素(如unshift/shift)的时间复杂度为O(n),因为需要移动所有元素
- 在数组末尾添加/删除元素(如push/pop)的时间复杂度为O(1)
- 对于大型数组,考虑使用类型化数组(TypedArray)以提高性能
总结
JavaScript数组是一种灵活且强大的数据结构,提供了多种创建和访问元素的方式。本文介绍了:
- 使用数组字面量、Array构造函数、Array.of()、Array.from()和扩展运算符创建数组
- 通过索引和at()方法访问数组元素
- 数组的基本属性和方法,如length、isArray()、toString()和join()
- 多维数组和类数组对象的概念
掌握这些基础知识将帮助你有效地使用JavaScript数组来存储和操作数据集合。