Javascript 数组基础用法
个人主页:康师傅前端面馆
JavaScript数组是前端开发中最重要的数据结构之一,无论是处理用户输入、管理应用状态,还是操作DOM元素,数组都扮演着核心角色。掌握数组的各种操作方法不仅能提高开发效率,还能帮助我们写出更简洁、更高效的代码。
1. 数组简介
数组是JavaScript中用于存储有序数据集合的对象,可以包含不同类型的数据。数组使用从0开始的数字索引来访问元素。
javascript
let mixedArray = [1, 'hello', true, {name: 'John'}, [1,2,3]];
console.log(mixedArray[0]); // 1
console.log(mixedArray[3].name); // John
2. 创建数组
javascript
// 字面量方式(推荐)
let arr1 = []; // 空数组
let arr2 = [1, 2, 3]; // 带初始值
// Array构造函数
let arr3 = new Array(); // 空数组
let arr4 = new Array(3); // 创建长度为3的空数组 [empty × 3]
let arr5 = new Array(1, 2, 3); // 创建包含1,2,3的数组
// Array.of() 方法(ES6)
let arr6 = Array.of(3); // [3] - 创建包含单个元素3的数组
let arr7 = Array.of(1, 2, 3); // [1, 2, 3]
// Array.from() 方法(ES6)
let arr8 = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
let arr9 = Array.from({length: 3}, (v, i) => i); // [0, 1, 2]
3. 常用数组方法
添加/删除元素
javascript
let fruits = ['apple', 'banana'];
// push() - 添加到末尾,返回新长度
let newLength = fruits.push('orange', 'grape'); // 添加多个元素
console.log(fruits); // ['apple', 'banana', 'orange', 'grape']
// pop() - 从末尾删除,返回删除的元素
let last = fruits.pop();
console.log(last); // 'grape'
console.log(fruits); // ['apple', 'banana', 'orange']
// unshift() - 添加到开头,返回新长度
let newLength2 = fruits.unshift('strawberry', 'mango');
console.log(fruits); // ['strawberry', 'mango', 'apple', 'banana', 'orange']
// shift() - 从开头删除,返回删除的元素
let first = fruits.shift();
console.log(first); // 'strawberry'
console.log(fruits); // ['mango', 'apple', 'banana', 'orange']
// splice() - 添加/删除指定位置元素
let arr = [1, 2, 3, 4, 5];
arr.splice(2, 1); // 从索引2开始删除1个元素
console.log(arr); // [1, 2, 4, 5]
arr.splice(2, 0, 'a', 'b'); // 从索引2开始添加元素
console.log(arr); // [1, 2, 'a', 'b', 4, 5]
其他常用方法
javascript
// concat() - 合并数组,不改变原数组
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = arr1.concat(arr2, [7, 8]);
console.log(combined); // [1, 2, 3, 4, 5, 6, 7, 8]
// slice() - 截取子数组,不改变原数组
let arr = [1, 2, 3, 4, 5];
let sub1 = arr.slice(1, 3); // 从索引1到索引3(不包含)
console.log(sub1); // [2, 3]
let sub2 = arr.slice(2); // 从索引2到末尾
console.log(sub2); // [3, 4, 5]
let copy = arr.slice(); // 浅拷贝整个数组
console.log(copy); // [1, 2, 3, 4, 5]
// indexOf() 和 lastIndexOf() - 查找元素索引
let arr = [1, 2, 3, 2, 4];
let index = arr.indexOf(2); // 1
let lastIndex = arr.lastIndexOf(2); // 3
let notFound = arr.indexOf(10); // -1
// includes() - 检查是否包含元素(ES2016)
let arr = [1, 2, 3];
let exists = arr.includes(2); // true
let notExists = arr.includes(5); // false
// find() 和 findIndex() - 根据条件查找(ES6)
let users = [
{id: 1, name: 'John'},
{id: 2, name: 'Jane'},
{id: 3, name: 'Bob'}
];
let user = users.find(u => u.id === 2); // {id: 2, name: 'Jane'}
let userIndex = users.findIndex(u => u.name === 'Bob'); // 2
4. 数组遍历
javascript
let arr = [1, 2, 3, 4, 5];
// for循环
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
// forEach方法 - 无法中途退出
arr.forEach((item, index, array) => {
console.log(`${index}: ${item}`);
});
// for...of循环 - 可以使用break/continue
for (let item of arr) {
if (item === 3) continue;
console.log(item);
}
// for...in循环 - 遍历索引(不推荐用于数组)
for (let index in arr) {
console.log(`${index}: ${arr[index]}`);
}
// map() - 创建新数组
let doubled = arr.map(x => x * 2); // [2, 4, 6, 8, 10]
// filter() - 过滤元素
let evens = arr.filter(x => x % 2 === 0); // [2, 4]
// some() 和 every() - 检查条件
let hasEven = arr.some(x => x % 2 === 0); // true
let allEven = arr.every(x => x % 2 === 0); // false
5. 数组转换
javascript
// join() - 数组转字符串
let arr = ['apple', 'banana', 'orange'];
let str1 = arr.join(); // "apple,banana,orange"
let str2 = arr.join(' - '); // "apple - banana - orange"
let str3 = arr.join(''); // "applebananaorange"
// split() - 字符串转数组
let str = "apple,banana,orange";
let arr1 = str.split(','); // ['apple', 'banana', 'orange']
let arr2 = str.split(',', 2); // ['apple', 'banana'] - 限制返回元素个数
// Array.from() - 类数组对象转数组
function example() {
let args = Array.from(arguments);
console.log(args);
}
example(1, 2, 3); // [1, 2, 3]
// 扩展运算符(ES6)
let str = "hello";
let arr = [...str]; // ['h', 'e', 'l', 'l', 'o']
let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = [...arr1, ...arr2]; // [1, 2, 3, 4]
6. 实用技巧
数组去重
javascript
// 使用Set(ES6)
let arr = [1, 2, 2, 3, 3, 4];
let unique = [...new Set(arr)]; // [1, 2, 3, 4]
// 使用filter和indexOf
let unique2 = arr.filter((item, index) => arr.indexOf(item) === index);
// 对象数组去重
let users = [
{id: 1, name: 'John'},
{id: 2, name: 'Jane'},
{id: 1, name: 'John'}
];
let uniqueUsers = users.filter((user, index, self) =>
index === self.findIndex(u => u.id === user.id)
);
数组排序
javascript
// 数字排序
let numbers = [10, 2, 30, 4];
let sorted = numbers.sort((a, b) => a - b); // [2, 4, 10, 30]
let desc = numbers.sort((a, b) => b - a); // [30, 10, 4, 2]
// 字符串排序
let fruits = ['banana', 'apple', 'cherry'];
let sortedStrings = fruits.sort(); // ['apple', 'banana', 'cherry']
// 对象排序
let users = [
{name: 'John', age: 30},
{name: 'Jane', age: 25},
{name: 'Bob', age: 35}
];
let sortedByAge = users.sort((a, b) => a.age - b.age);
数组过滤
javascript
let numbers = [1, 2, 3, 4, 5, 6];
// 基本过滤
let evens = numbers.filter(n => n % 2 === 0); // [2, 4, 6]
// 复杂条件过滤
let users = [
{name: 'John', age: 30, active: true},
{name: 'Jane', age: 25, active: false},
{name: 'Bob', age: 35, active: true}
];
let activeUsers = users.filter(user => user.active && user.age > 30);
数组映射
javascript
let numbers = [1, 2, 3, 4];
// 基本映射
let doubled = numbers.map(n => n * 2); // [2, 4, 6, 8]
// 对象映射
let users = [
{firstName: 'John', lastName: 'Doe'},
{firstName: 'Jane', lastName: 'Smith'}
];
let fullNames = users.map(user => `${user.firstName} ${user.lastName}`);
// ['John Doe', 'Jane Smith']
// 复杂映射
let products = [
{name: 'Apple', price: 1.2, quantity: 5},
{name: 'Banana', price: 0.8, quantity: 3}
];
let totalValues = products.map(p => ({
name: p.name,
totalValue: p.price * p.quantity
}));
数组求和
javascript
let numbers = [1, 2, 3, 4, 5];
// 基本求和
let sum = numbers.reduce((total, num) => total + num, 0); // 15
// 计算平均值
let average = numbers.reduce((total, num, _, arr) => total + num/arr.length, 0);
// 统计元素出现次数
let fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
let count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {}); // {apple: 3, banana: 2, orange: 1}
// 扁平化数组
let nested = [[1, 2], [3, 4], [5, 6]];
let flat = nested.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4, 5, 6]
// 或使用 flat() 方法(ES2019)
let flat2 = nested.flat(); // [1, 2, 3, 4, 5, 6]
其他实用方法
javascript
// reverse() - 反转数组
let arr = [1, 2, 3];
arr.reverse(); // [3, 2, 1]
// fill() - 填充数组
let arr = new Array(5).fill(0); // [0, 0, 0, 0, 0]
let arr2 = [1, 2, 3, 4, 5];
arr2.fill(0, 2, 4); // [1, 2, 0, 0, 5]
// copyWithin() - 复制数组内容
let arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3); // [4, 5, 3, 4, 5]
// entries(), keys(), values() - 迭代器方法(ES6)
let arr = ['a', 'b', 'c'];
for (let [index, value] of arr.entries()) {
console.log(`${index}: ${value}`);
}