Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 队列

作者:炼狱死神   发布日期:2026-04-17   浏览:8

// 创建一个简单的队列类
class Queue {
  constructor() {
    this.items = [];
  }

  // 向队列添加元素
  enqueue(element) {
    this.items.push(element);
  }

  // 从队列移除元素
  dequeue() {
    if (this.isEmpty()) {
      return "Underflow"; // 队列为空时返回"Underflow"
    }
    return this.items.shift();
  }

  // 查看队列前端的元素
  front() {
    if (this.isEmpty()) {
      return "No elements in Queue";
    }
    return this.items[0];
  }

  // 检查队列是否为空
  isEmpty() {
    return this.items.length === 0;
  }

  // 获取队列的大小
  size() {
    return this.items.length;
  }

  // 打印队列的所有元素
  printQueue() {
    let str = "";
    for (let i = 0; i < this.items.length; i++) {
      str += this.items[i] + " ";
    }
    return str;
  }
}

// 示例使用
const queue = new Queue();
console.log(queue.isEmpty()); // 输出: true

queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
console.log(queue.printQueue()); // 输出: 10 20 30

console.log(queue.size()); // 输出: 3
console.log(queue.front()); // 输出: 10

queue.dequeue();
console.log(queue.printQueue()); // 输出: 20 30

console.log(queue.isEmpty()); // 输出: false

这个代码示例展示了如何使用 JavaScript 实现一个简单的队列。队列是一种先进先出(FIFO)的数据结构,上述代码定义了一个 Queue 类,其中包含了一些常用的方法,如 enqueue(入队)、dequeue(出队)、front(查看队首元素)、isEmpty(检查队列是否为空)、size(获取队列大小)和 printQueue(打印队列中的所有元素)。

上一篇:js const用法

下一篇:js buffer

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站