数组基本操作(增删改查)
数组的创建与初始化
数组是JavaScript中最常用的数据结构之一,用于存储有序的元素集合。创建数组有多种方式:
// 字面量方式
const fruits = ['apple', 'banana', 'orange'];
// 构造函数方式
const numbers = new Array(1, 2, 3);
// 创建指定长度的空数组
const emptyArray = new Array(5); // 创建长度为5的空数组
初始化数组时可以包含任何类型的元素:
const mixedArray = [1, 'text', true, {name: 'John'}, [1, 2, 3]];
ES6引入了Array.of()方法,可以避免构造函数创建时的歧义:
const arr1 = Array.of(7); // [7]
const arr2 = Array(7); // [ , , , , , , ]
添加元素到数组
向数组添加元素有多种方法,每种方法有不同的适用场景:
push()方法 - 在数组末尾添加一个或多个元素:
const colors = ['red', 'green'];
colors.push('blue'); // ['red', 'green', 'blue']
colors.push('yellow', 'purple'); // 添加多个元素
unshift()方法 - 在数组开头添加一个或多个元素:
const numbers = [2, 3];
numbers.unshift(1); // [1, 2, 3]
numbers.unshift(-1, 0); // [-1, 0, 1, 2, 3]
splice()方法 - 在指定位置插入元素:
const letters = ['a', 'b', 'd'];
letters.splice(2, 0, 'c'); // 在索引2处插入'c'
// ['a', 'b', 'c', 'd']
concat()方法 - 合并数组:
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2); // [1, 2, 3, 4]
ES6扩展运算符也可以用于合并数组:
const newArray = [...arr1, ...arr2];
从数组中删除元素
删除数组元素同样有多种方法:
pop()方法 - 删除并返回数组的最后一个元素:
const stack = [1, 2, 3];
const last = stack.pop(); // last = 3, stack = [1, 2]
shift()方法 - 删除并返回数组的第一个元素:
const queue = [1, 2, 3];
const first = queue.shift(); // first = 1, queue = [2, 3]
splice()方法 - 删除指定位置的元素:
const items = ['a', 'b', 'c', 'd'];
items.splice(1, 2); // 从索引1开始删除2个元素
// items = ['a', 'd']
filter()方法 - 创建一个新数组,包含通过测试的元素:
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(n => n % 2 === 0);
// evens = [2, 4], numbers保持不变
delete操作符 - 删除元素但保留位置:
const arr = [1, 2, 3];
delete arr[1]; // arr = [1, empty, 3]
修改数组元素
修改数组元素最直接的方式是通过索引访问并重新赋值:
const fruits = ['apple', 'banana', 'cherry'];
fruits[1] = 'blueberry'; // ['apple', 'blueberry', 'cherry']
splice()方法也可以用于替换元素:
const colors = ['red', 'green', 'blue'];
colors.splice(1, 1, 'yellow'); // 替换索引1的元素
// colors = ['red', 'yellow', 'blue']
fill()方法 - 用固定值填充数组:
const arr = new Array(3).fill(0); // [0, 0, 0]
const arr2 = [1, 2, 3, 4];
arr2.fill(5, 1, 3); // [1, 5, 5, 4]
map()方法 - 创建一个新数组,其结果是原数组每个元素调用函数后的返回值:
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
// doubled = [2, 4, 6]
查询数组元素
查询数组元素有多种方法和技巧:
索引访问 - 最基本的查询方式:
const fruits = ['apple', 'banana', 'orange'];
const first = fruits[0]; // 'apple'
includes()方法 - 检查数组是否包含某个元素:
const numbers = [1, 2, 3];
numbers.includes(2); // true
numbers.includes(4); // false
indexOf()和lastIndexOf() - 查找元素索引:
const letters = ['a', 'b', 'c', 'a'];
letters.indexOf('a'); // 0
letters.lastIndexOf('a'); // 3
letters.indexOf('d'); // -1 (未找到)
find()和findIndex() - 使用测试函数查找:
const users = [
{id: 1, name: 'John'},
{id: 2, name: 'Jane'}
];
const user = users.find(u => u.id === 2); // {id: 2, name: 'Jane'}
const index = users.findIndex(u => u.id === 2); // 1
some()和every() - 测试数组元素是否满足条件:
const nums = [1, 2, 3, 4];
nums.some(n => n > 3); // true (至少有一个元素大于3)
nums.every(n => n > 0); // true (所有元素都大于0)
数组的遍历方法
遍历数组有多种方式,各有优缺点:
for循环 - 最基本的遍历方式:
const arr = ['a', 'b', 'c'];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
for...of循环 - ES6引入的更简洁的语法:
for (const item of arr) {
console.log(item);
}
forEach()方法 - 为每个元素执行函数:
arr.forEach((item, index) => {
console.log(`${index}: ${item}`);
});
map()方法 - 创建新数组:
const lengths = ['a', 'bb', 'ccc'].map(s => s.length);
// lengths = [1, 2, 3]
reduce()方法 - 将数组缩减为单个值:
const sum = [1, 2, 3, 4].reduce((acc, curr) => acc + curr, 0);
// sum = 10
数组的排序与反转
sort()方法 - 对数组元素进行排序:
const fruits = ['banana', 'apple', 'pear'];
fruits.sort(); // ['apple', 'banana', 'pear']
const numbers = [10, 2, 5, 1];
numbers.sort(); // [1, 10, 2, 5] (默认按字符串排序)
numbers.sort((a, b) => a - b); // [1, 2, 5, 10] (正确数字排序)
reverse()方法 - 反转数组顺序:
const arr = [1, 2, 3];
arr.reverse(); // [3, 2, 1]
数组的切片与连接
slice()方法 - 返回数组的一部分:
const arr = [1, 2, 3, 4, 5];
const part = arr.slice(1, 4); // [2, 3, 4] (不包括结束索引)
const copy = arr.slice(); // 创建浅拷贝
join()方法 - 将数组元素连接成字符串:
const words = ['Hello', 'world'];
const sentence = words.join(' '); // 'Hello world'
多维数组操作
JavaScript中的数组可以包含其他数组,形成多维数组:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// 访问元素
const middle = matrix[1][1]; // 5
// 遍历二维数组
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}
// 使用flat()扁平化数组
const flatArray = matrix.flat(); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
数组的实用方法
Array.isArray() - 检查变量是否为数组:
Array.isArray([]); // true
Array.isArray({}); // false
toString()和toLocaleString():
const arr = [1, 'a', new Date()];
arr.toString(); // "1,a,Thu Dec 01 2022..."
arr.toLocaleString(); // 本地化字符串表示
entries(), keys()和values() - 返回迭代器:
const arr = ['a', 'b', 'c'];
for (const [index, value] of arr.entries()) {
console.log(index, value);
}
数组的性能考虑
不同的数组操作有不同的性能特征:
- push/pop操作是O(1)时间复杂度
- shift/unshift操作是O(n)时间复杂度,因为需要移动所有元素
- 访问元素是O(1)时间复杂度
- 搜索元素在最坏情况下是O(n)时间复杂度
对于大型数组,频繁使用shift/unshift可能导致性能问题,可以考虑使用其他数据结构如链表。
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn