头疼的数组就该这样解决它

26 阅读1分钟

一、数组基础操作

1、创建数组

  • const arr1 = []; // 字面量创建
  • const arr2 = new Array(5); // 创建长度为5的空数组
  • const arr3 = Array.from('hello'); // 从类数组对象创建

2、增删元素

  • push()/pop() - 末端操作
  • unshift()/shift() - 首部操作
  • splice(start, deleteCount, ...items) - 任意位置增删

二、高阶操作方法

遍历转换

1、现代遍历方案

  • arr.forEach((item, index) => {});
  • const newArr = arr.map(item => item * 2);
  • const filtered = arr.filter(item => item > 10);

2、查找验证

  • arr.find(item => item.id === 100); // 返回首个匹配项
  • arr.some(item => item > 0); // 是否存在满足条件
  • arr.every(item => item < 100); // 是否全部满足

3、ES6+新特性

3.1、展开运算符 : const merged = [...arr1, ...arr2];

3.2、解构赋值: const [first, ...rest] = arr;

3.3、获取倒数第一个元素: Array.prototype.at() arr.at(-1);

三、性能优化技巧

1、大数据处理

1.1、使用TypedArray处理数值数组: const buffer = new ArrayBuffer(32);

1.2、使用Web Worker并行处理 : const floatArr = new Float64Array(buffer);

2、内存管理

2.1、清空数组最优方案 arr.length = 0;
2.2、避免内存泄漏 const largeArr = null; // 解除引用

四、实战案例

1、数组去重方案对比

1.1、Set方案(ES6) const unique = [...new Set(arr)];
1.2、filter方案(兼容性好) arr.filter((item, index) => arr.indexOf(item) === index);

2、多维数组处理

2.1、扁平化数组 const flatArr = arr.flat(Infinity);
2.2、矩阵转置 matrix[0].map((_, i) => matrix.map(row => row[i]));