js list实现
在 JavaScript 中实现列表(List)功能
JavaScript 中的数组(Array)可以很好地模拟列表(List)数据结构。数组提供了丰富的内置方法,支持动态增删元素、遍历、过滤等操作。
创建列表
使用数组字面量或构造函数创建列表:
// 使用字面量
const list1 = [1, 2, 3, 4];
// 使用构造函数
const list2 = new Array(1, 2, 3, 4);
添加元素
数组提供多种方法添加元素:
// 末尾添加
list1.push(5); // [1, 2, 3, 4, 5]
// 开头添加
list1.unshift(0); // [0, 1, 2, 3, 4, 5]
// 指定位置添加
list1.splice(2, 0, 1.5); // [0, 1, 1.5, 2, 3, 4, 5]
删除元素
同样有多种删除方式:
// 末尾删除
list1.pop(); // [0, 1, 1.5, 2, 3, 4]
// 开头删除
list1.shift(); // [1, 1.5, 2, 3, 4]
// 指定位置删除
list1.splice(1, 1); // [1, 2, 3, 4]
查找元素
// 按值查找索引
const index = list1.indexOf(3); // 2
// 按条件查找
const found = list1.find(item => item > 2); // 3
// 检查是否包含
const hasItem = list1.includes(2); // true
遍历列表
// forEach
list1.forEach(item => console.log(item));
// map
const doubled = list1.map(item => item * 2);
// filter
const filtered = list1.filter(item => item > 2);
列表长度
const length = list1.length; // 4
连接列表
const newList = list1.concat([5, 6, 7]);
排序列表
// 升序
list1.sort((a, b) => a - b);
// 降序
list1.sort((a, b) => b - a);
清空列表
list1.length = 0;
// 或
list1.splice(0, list1.length);
列表转字符串
const str = list1.join(', '); // "1, 2, 3, 4"
多维列表(矩阵)
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
性能考虑
对于大型列表操作,需要注意:

- 频繁在开头添加/删除(unshift/shift)会影响性能
- 大规模数据操作考虑使用TypedArray
- 大量查找操作可以考虑使用Set或Map
JavaScript数组已经提供了丰富的列表功能,可以满足大多数应用场景的需求。






