IT评测·应用市场-qidao123.com

标题: 前端数据结构 [打印本页]

作者: 东湖之滨    时间: 2024-9-7 22:15
标题: 前端数据结构
在前端开发中,常用的数据结构有助于高效地处理和管理数据。以下是一些常见的前端数据结构及其用途:

1. 数组(Array):


  1. const numbers = [1, 2, 3, 4, 5];
  2. numbers.push(6); // [1, 2, 3, 4, 5, 6]
  3. const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10, 12]
复制代码
2. 对象(Object):


  1. const person = { name: 'Alice', age: 25 };
  2. person.email = 'alice@example.com'; // { name: 'Alice', age: 25, email: 'alice@example.com' }
  3. const keys = Object.keys(person); // ['name', 'age', 'email']
复制代码
3. 聚集(Set):


  1. const uniqueNumbers = new Set([1, 2, 3, 4, 5, 5, 6]);
  2. uniqueNumbers.add(7); // Set { 1, 2, 3, 4, 5, 6, 7 }
  3. uniqueNumbers.has(3); // true
复制代码
4. 映射(Map):


  1. const map = new Map();
  2. map.set('name', 'Alice');
  3. map.set('age', 25);
  4. console.log(map.get('name')); // 'Alice'
复制代码
5. 队列(Queue):


  1. class Queue {
  2.   constructor() {
  3.     this.items = [];
  4.   }
  5.   enqueue(element) {
  6.     this.items.push(element);
  7.   }
  8.   dequeue() {
  9.     return this.items.shift();
  10.   }
  11.   isEmpty() {
  12.     return this.items.length === 0;
  13.   }
  14.   front() {
  15.     return this.items[0];
  16.   }
  17. }
  18. const queue = new Queue();
  19. queue.enqueue(1);
  20. queue.enqueue(2);
  21. console.log(queue.dequeue()); // 1
复制代码
6. 栈(Stack):


  1. class Stack {
  2.   constructor() {
  3.     this.items = [];
  4.   }
  5.   push(element) {
  6.     this.items.push(element);
  7.   }
  8.   pop() {
  9.     return this.items.pop();
  10.   }
  11.   isEmpty() {
  12.     return this.items.length === 0;
  13.   }
  14.   peek() {
  15.     return this.items[this.items.length - 1];
  16.   }
  17. }
  18. const stack = new Stack();
  19. stack.push(1);
  20. stack.push(2);
  21. console.log(stack.pop()); // 2
复制代码
7. 链表(Linked List):


  1. class Node {
  2.   constructor(value) {
  3.     this.value = value;
  4.     this.next = null;
  5.   }
  6. }
  7. class LinkedList {
  8.   constructor() {
  9.     this.head = null;
  10.   }
  11.   append(value) {
  12.     const newNode = new Node(value);
  13.     if (!this.head) {
  14.       this.head = newNode;
  15.     } else {
  16.       let current = this.head;
  17.       while (current.next) {
  18.         current = current.next;
  19.       }
  20.       current.next = newNode;
  21.     }
  22.   }
  23. }
  24. const list = new LinkedList();
  25. list.append(1);
  26. list.append(2);
复制代码
这些数据结构在前端开发中非常常见,选择合适的数据结构可以进步代码的效率和可维护性。


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




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4