JavaScript中数组是有序可变长对象,支持任意类型数据;常用字面量创建,操作分改变原数组(如push/splice)和不改变(如map/filter)两类,遍历推荐高阶函数,判断数组用Array.isArray()。
JavaScript中创建和操作数组非常直观,核心在于理解数组是**有序的、可变长度的对象**,能存储任意类型的数据。
最常见的是字面量语法,简洁高效:
const arr = [1, 'hello', true, {}];
const arr = new Array(1, 2, 3); 或 new Array(5)(会创建长度为5的空数组,注意不是[undefined, undefined, ...])Array.of(1, 2, 3) → [1, 2, 3];Array.from('abc') → ['a','b','c'];Array.from({length: 3}, (_, i) => i) → [0, 1, 2]
数组方法分两类:**改变原数组**(如 push/pop/shift/unshift/splice/sort/reverse)和**不改变原数组**(如 map/filter/
find/slice/concat)。
arr.push(4)(返回新长度),arr.pop()(返回被删元素)arr.unshift('first'),arr.shift()
arr.splice(1, 1, 'new')(从索引1删1个,插入'new')arr.indexOf('hello')(返回索引或-1),arr.includes(2)(返回布尔值)arr.slice(1, 3)(不修改原数组,返回新数组)避免用 for 循环硬写,优先选语义清晰的高阶函数:
arr.forEach(item => console.log(item))
arr.map(x => x * 2)
arr.filter(x => typeof x === 'number')
arr.reduce((sum, cur) => sum + cur, 0)
arr.every(x => x > 0),arr.some(x => x === 'hello')
数组不是真正的“类型”,而是对象,所以 typeof [] 是 "object"。判断是否为数组请用 Array.isArray(arr)。
[] 是真值(if([]){...} 会执行),但 arr.length === 0 才表示为空undefined(arr[100])arr.toString() 或 arr + '' 转字符串——它会用逗号拼接,且对嵌套数组可能意外扁平化JSON.parse(JSON.stringify(arr)) 有局限(丢失函数、undefined、Date等),更安全可用 structuredClone(arr)(现代浏览器支持)或扩展运算符 [...arr](仅浅拷贝)基本上就这些。掌握字面量创建、splice/map/filter/reduce 这几个核心,再留意是否改变原数组,日常开发就够用了。