在javascript中从队列中提取值

时间:2013-12-07 12:04:18

标签: javascript

我在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吗?

1 个答案:

答案 0 :(得分: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进行此类对象访问