Detailed introduction to queues in JavaScript (code examples)
This article brings you a detailed introduction (code example) about queues in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Definition of Queue
A queue is an ordered set of items that follows the first-in, first-out principle. The difference from a stack is that the stack does not matter whether it is pushed in or out. Stack operations are all performed on the top of the stack, while queues add elements to the end of the queue and remove elements from the top of the queue. A diagram is used to represent the process:
Use A more vivid example is: queuing service, the person who queues up first will always receive the service first, of course, regardless of the situation of queue jumping
Queue Creation
And Stack The creation is similar. First create a function representing the queue, and then define an array to save the elements in the queue:
function Queue() { let items = [] }
After creating the queue, you need to define some methods for it. Generally speaking, the queue contains the following methods:
enqueue(element): Add a new item to the end of the queue
dequeue(): Remove the first item of the queue and return Removed elements
front(): Returns the first item of the queue, and the queue does not make any changes
isEmpty(): If the queue There is no element in the return true, otherwise it returns false
size(): Returns the number of elements contained in the queue
Specific implementation:
function Queue() { let items = [] // 向队列的尾部添加新元素 this.enqueue = function (element) { items.push(element) } // 遵循先进先出原则,从队列的头部移除元素 this.dequeue = function () { return items.shift() } // 返回队列最前面的项 this.front = function () { return items[0] } // 返回队列是否为空 this.isEmpty = function () { return items.length === 0 } // 返回队列的长度 this.size = function () { return items.length } // 打印队列,方便观察 this.print = function () { console.log(items.toString()) } }
Use of queue
Next let’s look at the use of queue:
let queue = new Queue() queue.enqueue('a') queue.enqueue('b') queue.enqueue('c') queue.dequeue() queue.print()
First add three elements to the queue: a, b, c, then remove an element from the queue, and finally print the existing queue. Let us illustrate this process together:
es6 implements Queue
Same as implementing the Stack class, you can also use the es6 class syntax to implement the Queue class, use WeakMap to save private attribute items, and use closures to return the Queue class. Let’s look at the specific implementation:
let Queue = (function () { let items = new WeakMap class Queue { constructor () { items.set(this, []) } enqueue (element) { let q = items.get(this) q.push(element) } dequeue () { let q = items.get(this) return q.shift() } front () { let q = items.get(this) return q[0] } isEmpty () { let q = items.get(this) return q.length === 0 } size () { let q = items.get(this) return q.length } print () { let q = items.get(this) console.log(q.toString()) } } return Queue })() let queue = new Queue() queue.enqueue('a') queue.enqueue('b') queue.enqueue('c') queue.dequeue() queue.print()
Priority Queue
Priority queue, as its name implies: each element in the queue will have its own priority. When inserting, the insertion operation will be performed according to the order of priority, which is a bit different from the previous queue implementation. The difference is that there are more elements in the queue with priority attributes. Let’s look at the specific code:
function PriorityQueue() { let items = [] // 队列元素,多定义一个优先级变量 function QueueElement(element, priority) { this.element = element this.priority = priority } this.enqueue = function (element, priority) { let queueElement = new QueueElement(element, priority) let added = false for (let i = 0; i <p> When joining the queue, if the queue is empty, add it directly to the queue. Otherwise, compare, and the smaller priority will be given priority. The higher the level, the higher the priority is placed at the front of the queue. Let’s use a diagram to see the calling process: <br></p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/471/355/539/1550021327400018.png?x-oss-process=image/resize,p_40" class="lazy" title="1550021327400018.png" alt="Detailed introduction to queues in JavaScript (code examples)"></p><p style="max-width:90%"><strong>Circular Queue</strong></p><p> As the name suggests, the circular queue is: given a number, then iterates the queue, removes an item from the beginning of the queue, and then adds it to the end of the queue. When the loop reaches the given number, jump out of the loop and move from the head of the queue. Remove one item until there is one element left. Let’s look at the specific code: </p><pre class="brush:php;toolbar:false">unction Queue() { let items = [] this.enqueue = function (element) { items.push(element) } this.dequeue = function () { return items.shift() } this.front = function () { return items[0] } this.isEmpty = function () { return items.length === 0 } this.size = function () { return items.length } this.print = function () { console.log(items.toString()) } } function loopQueue(list, num) { let queue = new Queue() for (let i = 0; i<list.length> 1) { for (let j = 0; j<num console.log></num></list.length>
The above is the detailed content of Detailed introduction to queues in JavaScript (code examples). For more information, please follow other related articles on the PHP Chinese website!

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
