js list实现
在JavaScript中,列表(List)通常通过数组(Array)或对象(Object)实现,具体取决于需求。以下是几种常见的实现方式:
使用数组实现列表
数组是JavaScript中最直接的列表实现方式,支持动态增删元素和多种内置方法。

// 创建列表
const list = [1, 2, 3];
// 添加元素
list.push(4); // 末尾添加
list.unshift(0); // 开头添加
// 删除元素
list.pop(); // 移除末尾元素
list.shift(); // 移除开头元素
// 遍历列表
list.forEach(item => console.log(item));
// 查找元素
const index = list.indexOf(2); // 返回索引
使用对象实现键值对列表
若需键值对结构,可用对象模拟列表。

// 创建列表
const list = {
'a': 1,
'b': 2,
'c': 3
};
// 添加元素
list['d'] = 4;
// 删除元素
delete list['b'];
// 遍历列表
Object.keys(list).forEach(key => {
console.log(key, list[key]);
});
使用Map实现高性能列表
ES6的Map更适合频繁增删或键为非字符串的场景。
// 创建列表
const list = new Map();
list.set('a', 1);
list.set('b', 2);
// 删除元素
list.delete('a');
// 遍历列表
list.forEach((value, key) => {
console.log(key, value);
});
自定义列表类
封装一个简单的列表类,支持链式操作。
class List {
constructor() {
this.items = [];
}
add(item) {
this.items.push(item);
return this; // 支持链式调用
}
remove(item) {
this.items = this.items.filter(i => i !== item);
return this;
}
get(index) {
return this.items[index];
}
}
// 使用示例
const myList = new List();
myList.add(1).add(2).remove(1);
console.log(myList.get(0)); // 输出2
注意事项
- 数组适合顺序访问和索引操作,但删除中间元素需移动后续元素(性能影响)。
Map在频繁增删时性能更优,且键可以是任意类型。- 自定义类适合封装复杂逻辑,但需注意维护内部状态的一致性。






