js实现list
在JavaScript中实现列表(List)
JavaScript中没有内置的List数据结构,但可以通过数组(Array)或对象(Object)来模拟列表的功能。以下是几种常见的实现方式:
使用数组(Array)
数组是JavaScript中最常用的列表实现方式,提供了丰富的内置方法。
// 创建列表
const list = [1, 2, 3, 4, 5];
// 添加元素
list.push(6); // 末尾添加
list.unshift(0); // 开头添加
// 删除元素
list.pop(); // 删除末尾元素
list.shift(); // 删除开头元素
// 访问元素
console.log(list[2]); // 输出: 3
// 遍历列表
list.forEach(item => console.log(item));
使用对象(Object)实现链表
如果需要更复杂的列表结构(如链表),可以使用对象来实现。
// 链表节点
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
// 链表实现
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
// 添加节点
append(value) {
const newNode = new ListNode(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
// 遍历链表
traverse() {
let current = this.head;
while (current) {
console.log(current.value);
current = current.next;
}
}
}
// 使用示例
const linkedList = new LinkedList();
linkedList.append(1);
linkedList.append(2);
linkedList.append(3);
linkedList.traverse();
使用数组实现栈(Stack)
如果需要栈这种特殊的列表结构,可以用数组实现。
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.items.length === 0) return null;
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
}
// 使用示例
const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 输出: 2
使用数组实现队列(Queue)
队列也可以用数组实现,但要注意性能问题。
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
if (this.isEmpty()) return null;
return this.items.shift();
}
front() {
if (this.isEmpty()) return null;
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
}
// 使用示例
const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.dequeue()); // 输出: 1
使用ES6的Map或Set
对于需要唯一值或键值对的列表,可以使用Map或Set。
// Set实现唯一值列表
const uniqueList = new Set();
uniqueList.add(1);
uniqueList.add(2);
uniqueList.add(1); // 不会重复添加
console.log([...uniqueList]); // 输出: [1, 2]
// Map实现键值对列表
const kvList = new Map();
kvList.set('a', 1);
kvList.set('b', 2);
console.log(kvList.get('a')); // 输出: 1
注意事项
- 数组是最简单直接的列表实现方式,适合大多数场景
- 链表适合频繁插入删除的场景,但JavaScript中性能优势不明显
- 栈和队列是特殊的列表结构,可以根据需求选择实现
- Map和Set提供了额外的功能,如唯一性和键值对存储
根据具体需求选择合适的实现方式,通常数组就能满足大多数列表操作需求。







