数组

数组

image-20250728112044467

🥤1、基础知识

数组是什么

数组是对象的特殊形式,用于按照顺序存储多个值。

因此用 typeof arr 会得到 "object"

1
2
3
4
5
6
7
8
例如const arr = [10,20,30]
本质是带有【数字索引】和【length】键名的对象:
const obj = {
0: 10,
1: 20,
2: 30,
length: 3 // 自动维护,值是最大索引+1
};

🥤2、核心方法

🔹 一、增删改类

方法名 说明
push(item) 尾部添加元素,返回新长度
pop() 删除最后一个元素,返回该元素
unshift(item) 头部添加元素,返回新长度
shift() 删除第一个元素,返回该元素
splice(start, deleteCount, ...items) 删除/插入/替换元素(非常强大)
fill(value, start, end) 用值填充数组

🔹 二、遍历/查找类

方法名 说明
forEach(callback) 遍历每个元素(不能中断)
map(callback) 返回处理后的新数组
filter(callback) 返回符合条件的元素数组
find(callback) 返回第一个符合条件的元素
findIndex(callback) 返回第一个符合条件元素的索引
some(callback) 只要有一个符合就返回 true
every(callback) 所有都符合才返回 true

🔹 三、查找索引相关

方法名 说明
includes(value) 是否包含某值
indexOf(value) 返回首次出现的索引,没有返回 -1
lastIndexOf(value) 返回最后一次出现的索引

🔹 四、转换类

方法名 说明
join(separator) 用分隔符拼接成字符串
toString() 将数组转换为字符串(用逗号连接)
flat(depth) 展开嵌套数组
flatMap(callback) 先 map 再 flat

🔹 五、排序/重组类

方法名 说明
sort(compareFn) 排序(默认按字符串)
reverse() 反转数组
slice(start, end) 浅拷贝部分元素
concat(...arrays) 合并数组,返回新数组

🔹 六、迭代器相关(ES6+)

方法名 说明
entries() 返回索引+值的迭代器
keys() 返回索引的迭代器
values() 返回值的迭代器

🥤3、高级特性

🔹 一、稀疏数组

稀疏数组

在上面创建数组的情况中,实际长度101,但是只有索引100处有值,其余的索引位置是空槽。

1
2
3
console.log(arr[0]);     // 输出 undefined(但实际是 empty)
console.log(0 in arr); // 输出 false(说明索引 0 未被赋值)
console.log(100 in arr); // 输出 true(索引 100 有值)

undefined 有什么区别?

1
2
空位不占用内存,in操作符检测是false,数组方法可能会被跳过,如map,forEach,filter,Object.keys
undefined是主动赋值,占用内存,in操作符检测是true

稀疏数组的遍历

遍历方法 能否遍历空槽 说明
for 循环 ✅ 可以 空槽输出undefined
for...of ✅ 可以 空槽输出undefined
for...in ❌ 跳过空槽 只遍历有值的索引,并且是字符串格式的索引
forEach ❌ 跳过空槽 不处理空槽
map / filter ❌ 跳过空槽 不会对空槽调用回调,但保留空槽位置
Object.keys() ❌ 跳过空槽 只遍历有值的索引

所以需要跳过稀疏数组的空槽,使用for in或者forEach。

如果使用for循环的话,通过【in操作符】过滤:

1
2
3
4
5
6
const arr = [1, , 3];
for (let i = 0; i < arr.length; i++) {
if (i in arr) {
console.log(arr[i]); // 输出 1 和 3,跳过空槽
}
}

或者使用【hasOwnProperty】方法过滤:

1
2
3
4
5
for (let i = 0; i < arr.length; i++) {
if (arr.hasOwnProperty(i)) {
console.log(arr[i]); // 输出 1 和 3,跳过空槽
}
}

🔹 二、类数组

像数组一样有索引、length属性,但不具备数组的方法!

1
2
3
4
function test() {
console.log(arguments); // 类数组对象
}

如何转换为数组

1
Array.from(arguments)

🔹 三、数组迭代器

数组迭代器是一个对象,实现了迭代器协议,即拥有next()方法,每次调用都返回一个包含value和done属性的对象。value:当前迭代的值,done:布尔值,表示是否已完成迭代。

获取数组迭代器

1
2
const arr = ['a', 'b', 'c'];
const iterator = arr[Symbol.iterator](); // 获取数组的默认迭代器

使用迭代器

1
2
3
4
console.log(iterator.next()); // { value: 'a', done: false }
console.log(iterator.next()); // { value: 'b', done: false }
console.log(iterator.next()); // { value: 'c', done: false }
console.log(iterator.next()); // { value: undefined, done: true }

应用场景

1
2
3
4
for of循环
展开运算符 [...arr]
解构赋值 const [first,second] = arr
Array.from

返回迭代器的方法

1
keys()、values()、entries()

🔹 四、数组解构

1
const [a, b] = [1, 2];

🔹 五、展开运算符

1
2
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]