js中数组怎么实现
数组的创建
在 JavaScript 中,数组可以通过多种方式创建。最常见的方式是使用数组字面量或 Array 构造函数。
// 使用数组字面量
const arr1 = [1, 2, 3];
// 使用 Array 构造函数
const arr2 = new Array(1, 2, 3);
// 创建空数组
const arr3 = [];
const arr4 = new Array();
数组的基本操作
数组的基本操作包括访问元素、修改元素、获取数组长度等。
const arr = [1, 2, 3];
// 访问元素
console.log(arr[0]); // 输出: 1
// 修改元素
arr[1] = 4;
console.log(arr); // 输出: [1, 4, 3]
// 获取数组长度
console.log(arr.length); // 输出: 3
数组的常用方法
JavaScript 提供了许多内置方法用于操作数组。
添加和删除元素
const arr = [1, 2, 3];
// 添加元素到末尾
arr.push(4);
console.log(arr); // 输出: [1, 2, 3, 4]
// 删除末尾元素
arr.pop();
console.log(arr); // 输出: [1, 2, 3]
// 添加元素到开头
arr.unshift(0);
console.log(arr); // 输出: [0, 1, 2, 3]
// 删除开头元素
arr.shift();
console.log(arr); // 输出: [1, 2, 3]
合并数组
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2);
console.log(merged); // 输出: [1, 2, 3, 4]
遍历数组

const arr = [1, 2, 3];
// 使用 forEach
arr.forEach(item => console.log(item));
// 使用 map
const doubled = arr.map(item => item * 2);
console.log(doubled); // 输出: [2, 4, 6]
查找和过滤
const arr = [1, 2, 3, 4];
// 查找元素
const found = arr.find(item => item > 2);
console.log(found); // 输出: 3
// 过滤数组
const filtered = arr.filter(item => item % 2 === 0);
console.log(filtered); // 输出: [2, 4]
多维数组
JavaScript 支持多维数组,可以通过嵌套数组实现。
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][1]); // 输出: 5
数组的解构赋值
ES6 引入了数组的解构赋值功能,可以方便地从数组中提取值。
const arr = [1, 2, 3];
const [a, b, c] = arr;
console.log(a, b, c); // 输出: 1 2 3
数组的扩展运算符
扩展运算符 ... 可以用于展开数组,常用于合并数组或传递参数。

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // 输出: [1, 2, 3, 4]
数组的排序和反转
JavaScript 提供了 sort 和 reverse 方法用于排序和反转数组。
const arr = [3, 1, 4, 2];
// 排序
arr.sort((a, b) => a - b);
console.log(arr); // 输出: [1, 2, 3, 4]
// 反转
arr.reverse();
console.log(arr); // 输出: [4, 3, 2, 1]
数组的切片和拼接
slice 方法用于截取数组的一部分,splice 方法用于删除或替换数组中的元素。
const arr = [1, 2, 3, 4, 5];
// 切片
const sliced = arr.slice(1, 3);
console.log(sliced); // 输出: [2, 3]
// 拼接
arr.splice(1, 2, 'a', 'b');
console.log(arr); // 输出: [1, 'a', 'b', 4, 5]
数组的迭代方法
ES6 引入了许多新的数组迭代方法,如 findIndex、some、every 等。
const arr = [1, 2, 3, 4];
// 查找索引
const index = arr.findIndex(item => item === 3);
console.log(index); // 输出: 2
// 检查是否至少有一个元素满足条件
const hasEven = arr.some(item => item % 2 === 0);
console.log(hasEven); // 输出: true
// 检查是否所有元素都满足条件
const allEven = arr.every(item => item % 2 === 0);
console.log(allEven); // 输出: false
数组的扁平化
flat 方法可以将多维数组扁平化。
const arr = [1, [2, [3, [4]]]];
const flattened = arr.flat(2);
console.log(flattened); // 输出: [1, 2, 3, [4]]






