【发布时间】:2019-12-30 22:59:38
【问题描述】:
我有两个函数,一个用于出队,一个用于将用户输入的项目从数组中排入队列。
我对队列的了解
我对队列的了解非常有限,我知道它们类似于堆栈,但不是后进先出 (LIFO),因为堆栈是先进先出 (FIFO),所以基本上首先进入数组的任何元素都将首先从数组中取出。
我现在正在尝试什么
我现在要做的是使用 Enqueue 按钮,我将项目添加到数组中,同时每次按下按钮将变量计数增加 1,以便将每个新用户输入添加到下一个数组位置。在 dequeue 函数中,我通过递增 dequeueCount 变量将 dequeue 数组的每个元素设置为等于原始数组的每个元素。
有什么问题 这里的问题是,当我按下出队按钮时,我基本上需要重新索引所有内容,以便在我将索引 1 处的元素出队后,现在采用位置索引 0,基本上我总是想将元素 0 处的项目出队。
queue.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-queue',
templateUrl: './queue.component.html',
styleUrls: ['./queue.component.css']
})
export class QueueComponent implements OnInit {
@Input() userInput: String
array = []
arrayCount = 0
dequeueCount = 0
dequeueArray = []
dequeued = null
constructor() { }
ngOnInit() {
}
enQ() {
this.array[this.arrayCount++] = this.userInput;
}
deQ() {
deQ() {
if (this.arrayCount > 0) {
this.dequeueArray[this.dequeueCount++] = this.array[this.dequeueCount-1]
this.dequeued = this.dequeueArray[this.dequeueCount-1]
this.arrayCount--
}
else {
this.dequeued = "There is nothing else to dequeue"
}
}
}
我试图在这里显示数组的当前值
<div>
<label for="userInput">Input to Array:
<input [(ngModel)]="userInput" type="text">
</label><br>
<button (click)="enQ()">Enqueue</button>
<button (click)="deQ()">Dequeue</button>
<h3>Arrays</h3>
<p *ngFor = "let item of array"> {{ array }} </p>
<h3>Dequeued Item</h3>
<p> {{ dequeued}} </p>
</div>
当我按下入队函数时,一切似乎都正常工作,并且在正确位置向数组添加了一个值,因此入队函数没有问题,但是使用出队函数,我需要以某种方式使项目出队并从数组中删除第一项并重新显示 {{ array }} 并删除出列项。
【问题讨论】:
-
对于那些告诉我方法很复杂的人,我知道这是基于为我设置的仅使用数组、计数和index,不使用push、shift等内置函数
标签: arrays angular typescript queue