js列表实现
JavaScript 列表实现方法
JavaScript 中的列表可以通过数组(Array)或对象(Object)实现。以下是几种常见的实现方式:
使用数组实现列表
数组是最直接的列表实现方式,提供了一系列内置方法操作元素。
const list = [1, 2, 3, 4];
list.push(5); // 添加元素到末尾
list.pop(); // 移除末尾元素
list.unshift(0); // 添加元素到开头
list.shift(); // 移除开头元素
使用对象实现键值对列表
当需要键值对结构时,可以使用对象存储数据。

const list = {
key1: 'value1',
key2: 'value2'
};
list.key3 = 'value3'; // 添加新键值
delete list.key2; // 删除键值
使用链表数据结构
如果需要更复杂的操作(如高效插入/删除),可以手动实现链表。
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
append(value) {
const newNode = new Node(value);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
}
使用 ES6 Map 实现有序列表
Map 可以保持插入顺序,适合需要顺序保证的场景。

const list = new Map();
list.set('key1', 'value1');
list.set('key2', 'value2');
list.delete('key1');
使用 Array 方法实现高级操作
JavaScript 数组提供 map、filter、reduce 等方法实现复杂操作。
const numbers = [1, 2, 3];
const doubled = numbers.map(x => x * 2); // [2, 4, 6]
const evens = numbers.filter(x => x % 2 === 0); // [2]
const sum = numbers.reduce((acc, x) => acc + x, 0); // 6
选择哪种实现方式取决于具体需求:
- 简单有序集合:使用数组
- 键值对存储:使用对象或 Map
- 频繁插入/删除:考虑链表
- 需要顺序保证:使用 Map






