I am just trying to learn JavaScript. I want to design a queue which takes the following format:
[{(0,0),0}], [{(0,1),1}], [{(0,2),2}]
So I tried to define the queue in the following way, but obviously it's not correct
var queue = [{}] ;
I am just trying to learn JavaScript. I want to design a queue which takes the following format:
[{(0,0),0}], [{(0,1),1}], [{(0,2),2}]
So I tried to define the queue in the following way, but obviously it's not correct
var queue = [{}] ;
Firstly, there is no "couple" data-strucuture in JS, so your (0,1)
must be an array [0,1]
, an object: {x: 0, y: 1}
or a custom type (see below).
In javascript, structures aren't strongly typed, so you just have to define if the root is an array or an object. In this case, it seems to be an array.
var queue = [];
Then, push in the queue what you need. For example : (I invented the field names, fits them to your use case)
var element1 = {coords: [0, 0], val: 0 };
queue.push(element1);
var element2 = {coords: [0, 1], val: 1 };
queue.push(element2);
Like I said, you can use another representation, like: [[0,0], 0]
, or define a custom type (Object-oriented).
function MyType(coords, val) {
this.coords = coords;
this.val = val;
}
function Couple(x, y) {
this.x = x;
this.y = y;
}
queue.push(new MyType(new Couple(1, 2), 3))
对于要使用的队列,array
用于保留值
var myQueue = [] //Empty array
通过将某些内容推送到数组中来将其添加到队列中
myQueue.push(new Person(...))
通过将其移出数组来从队列中获取某些内容
var nextInLine = myQueue.shift()
您可以按如下方式构建队列:
function Queue () {
this.dataStore = [];
this.enqueue = enqueue;
this.dequeue = dequeue;
this.front = front;
this.back = back;
this.toString = toString;
this.empty = empty;
}
// Insetion
function enqueue(element){
this.dataStore.push(element);
}
// Deletion
function dequeue(){
this.dataStore.shift();
}
// front
function front(){
return this.dataStore[0];
}
//back
function back(){
return this.dataStore[this.dataStore.length-1];
}
//toString
function toString(){
var retStr = '';
for(var i = 0; i < this.dataStore.length; i++){
retStr = retStr + this.dataStore[i]
}
return retStr;
}
//empty
function empty(){
if(this.dataStore.length === 0) {
return true;
}
return false;
}
现在将其用作构造方法,var q = new Queue()。