js列表实现
列表数据结构的基本概念
列表是一种线性数据结构,元素按顺序排列,支持动态增删。在JavaScript中,列表可通过数组或对象模拟,核心操作包括添加、删除、访问和遍历。
使用数组实现列表
JavaScript数组原生支持列表操作:
// 创建列表
const list = [1, 2, 3];
// 添加元素(末尾)
list.push(4); // [1, 2, 3, 4]
// 删除元素(按索引)
list.splice(1, 1); // 删除索引1的元素,结果为[1, 3, 4]
// 访问元素
console.log(list[0]); // 输出1
// 遍历列表
list.forEach(item => console.log(item));
使用对象模拟列表(键值存储)
适用于需要非数字键的场景:
const list = {};
let index = 0;
// 添加元素
list[index++] = 'a';
list[index++] = 'b';
// 删除元素
delete list[0]; // 删除键为0的元素
// 遍历列表
Object.values(list).forEach(item => console.log(item));
自定义列表类(封装核心方法)
实现一个可扩展的列表类:

class CustomList {
constructor() {
this.items = [];
}
add(item) {
this.items.push(item);
}
remove(index) {
if (index >= 0 && index < this.items.length) {
this.items.splice(index, 1);
}
}
get(index) {
return this.items[index];
}
size() {
return this.items.length;
}
}
// 使用示例
const myList = new CustomList();
myList.add('x');
myList.add('y');
console.log(myList.get(1)); // 输出'y'
性能优化与注意事项
- 动态扩容:JavaScript数组自动处理内存,但频繁插入/删除可能触发多次内存分配。
- 时间复杂度:
push/pop为 O(1),shift/unshift为 O(n)。splice平均 O(n),需谨慎使用。
- 不可变操作:考虑使用扩展运算符或
concat避免原数组修改:const newList = [...list, 'newItem']; // 添加元素且不改变原列表






