我如何循环遍历对象数组

时间:2015-12-10 10:53:32

标签: javascript arrays

这里我想循环遍历包含对象元素的数组。但我的问题是我无法将spritearray[i] =(应该是)Ncardinal传递到函数文本(label = (Ncardinal = {"name": "North", "lat": 0, "lon": 360}))

var sprite, label;
var radius = 1;
function text(label, radius)
{
 this.position.x = label.lat;
 this.position.y = label.lon;
};
var Ncardinal = {"name": "North", "lat": 0, "lon": 360};
var Scardinal = {"name": "South", "lat": 0, "lon": 180};
var Ecardinal = {"name": "East", "lat": 0, "lon": 90};
var spritearray = [Ncardinal, Scardinal, Ecardinal];
for(var i=0; i<spritearray.length; i++)
{
 sprite = new text(spritearray[i], radius);
}

1 个答案:

答案 0 :(得分:0)

在向其添加属性之前,您需要定义this.position

这是一个将精灵位置输出到控制台的工作版本:

var sprite, label;
var radius = 1;

function text(label, radius) {
  this.position = {};           // <---- this is the key
  this.position.x = label.lat;
  this.position.y = label.lon;
  
  // or all in one line
  // this.position = {x: label.lat, y: label.lon};
};
var Ncardinal = {
  "name": "North",
  "lat": 0,
  "lon": 360
};
var Scardinal = {
  "name": "South",
  "lat": 0,
  "lon": 180
};
var Ecardinal = {
  "name": "East",
  "lat": 0,
  "lon": 90
};
var spritearray = [Ncardinal, Scardinal, Ecardinal];
for (var i = 0; i < spritearray.length; i++) {
  sprite = new text(spritearray[i], radius);
  console.log(sprite);
}