# 创建数组

javaScript中怎么创建数组?那种开发中最常用?直接给出实例就行。

# 1. 数组字面量(最常用)

const arr1 = []; // 空数组
const arr2 = [1, 2, 3, 4, 5]; // 包含数字的数组
const arr3 = ['a', 'b', 'c']; // 包含字符串的数组
const arr4 = [1, 'hello', true, null]; // 混合类型数组
1
2
3
4

# 2. Array 构造函数

const arr1 = new Array(); // 空数组
const arr2 = new Array(1, 2, 3); // [1, 2, 3]
const arr3 = new Array(5); // 创建长度为5的空数组
1
2
3

# 3. Array.of() 方法

const arr1 = Array.of(1, 2, 3); // [1, 2, 3]
const arr2 = Array.of(5); // [5] 与 new Array(5) 不同
1
2

# 4. Array.from() 方法

// 从类数组对象创建
const arr1 = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
const arr2 = Array.from({ length: 3 }); // [undefined, undefined, undefined]
const arr3 = Array.from({ length: 3 }, (_, i) => i); // [0, 1, 2]
1
2
3
4

# 5. 扩展运算符

const arr1 = [...'hello']; // ['h', 'e', 'l', 'l', 'o']
const arr2 = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]
1
2

# 🎯 开发中最常用:数组字面量

# 实际开发示例:

// 用户列表
const users = ['张三', '李四', '王五'];

// 商品信息
const products = [
  { id: 1, name: '手机', price: 1999 },
  { id: 2, name: '电脑', price: 4999 }
];

// 数字序列
const numbers = [1, 2, 3, 4, 5];

// 混合数据
const mixed = [1, '文本', true, { key: 'value' }];

// 动态创建
const dynamicArray = [];
dynamicArray.push('新元素');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

推荐使用数组字面量的原因:

  • 语法简洁直观
  • 性能更好
  • 可读性高
  • 不易出错(避免构造函数的一些陷阱)

在日常开发中,95% 以上的场景都使用数组字面量来创建数组。

Last Updated: 12/4/2025, 10:23:47 AM