东湖之滨 发表于 2024-9-7 22:15:32

前端数据结构

在前端开发中,常用的数据结构有助于高效地处理和管理数据。以下是一些常见的前端数据结构及其用途:

1. 数组(Array):



[*]用于存储有序的元素聚集,可以是任何范例的数据。
[*]常用方法:push、pop、shift、unshift、map、filter、reduce、forEach 等。
const numbers = ;
numbers.push(6); //
const doubled = numbers.map(num => num * 2); //
2. 对象(Object):



[*]用于存储键值对,键是字符串或符号,值可以是任何范例的数据。
[*]常用方法:Object.keys、Object.values、Object.entries、hasOwnProperty 等。
const person = { name: 'Alice', age: 25 };
person.email = 'alice@example.com'; // { name: 'Alice', age: 25, email: 'alice@example.com' }
const keys = Object.keys(person); // ['name', 'age', 'email']
3. 聚集(Set):



[*]用于存储唯一值的聚集,可以是任何范例的数据。
[*]常用方法:add、delete、has、clear 等。
const uniqueNumbers = new Set();
uniqueNumbers.add(7); // Set { 1, 2, 3, 4, 5, 6, 7 }
uniqueNumbers.has(3); // true
4. 映射(Map):



[*]用于存储键值对,键和值可以是任何范例的数据。
[*]常用方法:set、get、has、delete、clear 等。
const map = new Map();
map.set('name', 'Alice');
map.set('age', 25);
console.log(map.get('name')); // 'Alice'
5. 队列(Queue):



[*]一种先辈先出(FIFO)的数据结构。
[*]可以利用数组来实现队列。
class Queue {
constructor() {
    this.items = [];
}
enqueue(element) {
    this.items.push(element);
}
dequeue() {
    return this.items.shift();
}
isEmpty() {
    return this.items.length === 0;
}
front() {
    return this.items;
}
}

const queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.dequeue()); // 1
6. 栈(Stack):



[*]一种后进先出(LIFO)的数据结构。
[*]可以利用数组来实现栈。
class Stack {
constructor() {
    this.items = [];
}
push(element) {
    this.items.push(element);
}
pop() {
    return this.items.pop();
}
isEmpty() {
    return this.items.length === 0;
}
peek() {
    return this.items;
}
}

const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 2
7. 链表(Linked List):



[*]一种线性数据结构,此中每个元素包罗一个指向下一个元素的引用。
[*]可以实现单向链表和双向链表。
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;
    } else {
      let current = this.head;
      while (current.next) {
      current = current.next;
      }
      current.next = newNode;
    }
}
}

const list = new LinkedList();
list.append(1);
list.append(2);
这些数据结构在前端开发中非常常见,选择合适的数据结构可以进步代码的效率和可维护性。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 前端数据结构