JavaScript 数组创建
数组是JavaScript中最常用的数据结构之一,它允许你在单个变量中存储多个元素。无论你是要存储用户列表、产品清单,还是任何需要有序集合的数据,数组都是你的好帮手。
在本教程中,我们将探索在JavaScript中创建数组的各种方法,从基本方法到更高级的技术,并讨论每种方法的优缺点和适用场景。
什么是JavaScript数组?
在深入了解如何创建数组之前,让我们先简单了解一下JavaScript数组是什么:
- 数组是一种特殊类型的对象
- 它用于按顺序存储多个值
- 可以存储任何类型的数据(字符串、数字、对象、其他数组等)
- 数组中的每个项目都有一个从0开始的索引
创建数组的方法
1. 使用数组字面量(推荐)
最简单、最常用的创建数组方法是使用数组字面量(方括号 []
):
// 空数组
const emptyArray = [];
// 包含数字的数组
const numbers = [1, 2, 3, 4, 5];
// 包含不同数据类型的数组
const mixed = [1, "Hello", true, null, {name: "John"}, [10, 20]];
console.log(numbers); // [1, 2, 3, 4, 5]
console.log(mixed); // [1, "Hello", true, null, {name: "John"}, [10, 20]]
提示
数组字面量是创建数组最简洁、最优雅的方式,也是大多数JavaScript开发者首选的方法。
2. 使用Array构造函数
另一种创建数组的方式是使用Array
构造函数:
// 创建空数组
const emptyArray = new Array();
// 创建指定长度的数组(所有元素都是undefined)
const arrayWithLength = new Array(5);
// 创建带有初始值的数组
const numbers = new Array(1, 2, 3, 4, 5);
console.log(emptyArray); // []
console.log(arrayWithLength); // [empty × 5]
console.log(numbers); // [1, 2, 3, 4, 5]
注意
使用Array构造函数时要小心。如果只传递一个数字参数,它会创建一个长度为该数字的空数组,而不是包含该数字的数组!
const a = new Array(3); // 创建一个长度为3的空数组
const b = new Array(1, 2, 3); // 创建一个包含1, 2, 3的数组
3. 使用Array.of()方法
ES6引入了Array.of()
方法,它创建一个具有可变数量参数的新数组实例,而不考虑参数的数量或类型:
const numbers = Array.of(1, 2, 3, 4, 5);
const singleNumber = Array.of(5);
console.log(numbers); // [1, 2, 3, 4, 5]
console.log(singleNumber); // [5]
Array.of()
解决了Array()
构造函数的问题,始终创建包含传入参数的数组,即使只有一个数字参数。
4. 使用Array.from()方法
Array.from()
方法可以从类数组对象(如字符串、Set、Map或函数参数对象)或可迭代对象创建一个新的数组实例:
// 从字符串创建数组
const arrayFromString = Array.from('hello');
// 从Set创建数组
const arrayFromSet = Array.from(new Set([1, 2, 3, 3, 4]));
// 使用映射函数
const doubledNumbers = Array.from([1, 2, 3], x => x * 2);
console.log(arrayFromString); // ["h", "e", "l", "l", "o"]
console.log(arrayFromSet); // [1, 2, 3, 4]
console.log(doubledNumbers); // [2, 4, 6]
Array.from()
非常强大,特别是当你需要将类数组对象转换为真正的数组时。
5. 使用展开运算符(Spread Operator)
ES6引入的展开运算符(...
)也可以用于创建数组:
// 从其他可迭代对象创建数组
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];
// 从字符串创建数组
const chars = [...'hello'];
console.log(arr2); // [1, 2, 3, 4, 5, 6]
console.log(chars); // ["h", "e", "l", "l", "o"]
填充数组的方法
有时我们需要创建一个预填充值的数组。以下是几种方法:
1. 使用Array.fill()方法
// 创建长度为5,值全为0的数组
const zeroArray = new Array(5).fill(0);
// 填充数组的一部分
const partiallyFilledArray = [1, 2, 3, 4, 5];
partiallyFilledArray.fill(0, 2, 4); // 从索引2到索引4(不包含)填充0
console.log(zeroArray); // [0, 0, 0, 0, 0]
console.log(partiallyFilledArray); // [1, 2, 0, 0, 5]