js实现数组
数组创建与初始化
在JavaScript中,数组可以通过多种方式创建和初始化。最直接的方法是使用数组字面量:
const arr1 = []; // 空数组
const arr2 = [1, 2, 3]; // 包含三个元素的数组
const arr3 = new Array(5); // 长度为5的空数组
const arr4 = Array.of(1, 2, 3); // 类似于字面量创建
数组元素访问与修改
数组元素通过索引访问和修改,索引从0开始:
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits[1]); // 输出: banana
fruits[2] = 'grape'; // 修改第三个元素
console.log(fruits); // 输出: ['apple', 'banana', 'grape']
常用数组方法
JavaScript提供了丰富的数组操作方法:
添加/删除元素
const numbers = [1, 2, 3];
numbers.push(4); // 末尾添加元素
numbers.pop(); // 移除最后一个元素
numbers.unshift(0); // 开头添加元素
numbers.shift(); // 移除第一个元素
数组遍历
const colors = ['red', 'green', 'blue'];
colors.forEach(color => console.log(color));
const doubled = numbers.map(num => num * 2);
const evens = numbers.filter(num => num % 2 === 0);
查找与判断
const found = colors.find(color => color === 'green');
const hasRed = colors.includes('red');
const index = colors.indexOf('blue');
多维数组实现
JavaScript通过数组嵌套实现多维数组:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // 输出: 6
数组解构与扩展
ES6引入的解构和扩展语法简化了数组操作:
const [first, second] = ['a', 'b', 'c'];
const newArr = [...firstArr, ...secondArr];
性能优化技巧
对于大型数组操作,考虑以下优化方法:

- 使用
for循环代替forEach进行大批量操作 - 预先分配数组长度
new Array(size)减少动态扩容 - 使用TypedArray处理数值型数据
- 合理使用
reduce方法替代多次循环






