用javascript从队列中提取值

Extracting values from a queue in javascript

本文关键字:提取 队列 javascript      更新时间:2024-04-12

我在java脚本中创建了一个队列,该队列以以下方式存储

function MyType(coords, val) {
  this.coords = coords;
  this.val = val;
}
function Couple(x, y) {

  this.x = x;
  this.y = y ;
}
var queue =  [];
villianXPos = 4;
villianYPos = 4;
queue.push(new MyType(new Couple(villianXPos,villianYPos, 0))); 

现在我想在单独的变量中提取坐标和val

当我做时

 var element = queue.shift();

元素正在获取整个值4,4,0

有可能在我的元素变量中只得到4,4,在另一个变量中得到0吗?

假设

queue.push(new MyType(new Couple(villianXPos,villianYPos, 0))); 

实际上应该是

queue.push(new MyType(new Couple(villianXPos,villianYPos), 0)); 

然后

function MyType(coords, val) {
  this.coords = coords;
  this.val = val;
}
function Couple(x, y) {
  this.x = x;
  this.y = y ;
}
var queue =  [];
villianXPos = 4;
villianYPos = 4;
queue.push(new MyType(new Couple(villianXPos,villianYPos), 0)); 
var meh = queue.shift();
console.log(meh.coords);
//yields Couple {x: 4, y: 4} 
console.log(meh.coords.x);
//yields 4
console.log(meh.val);
//yields 0
console.log(queue);
//yields the remainder of the queue, in this case empty array [] 

然而,对于这种对象访问

,使用getter/setter是一种很好的做法