-2

Here I wanted to loop through my array consisting elements as Objects. But my problem is that I was unable to pass spritearray[i] =(which should be) Ncardinal into the function text(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);
}
rajesh
  • 7
  • 6
  • 2
    your code makes no sense, because of the two opened curly brackets and the return inbetween – Nina Scholz Dec 10 '15 at 10:57
  • `sprite` should be an array `[]` where you `push` items. with your code, you create the `text` object and put it in sprite variable, only keeping the last one. – Hacketo Dec 10 '15 at 10:57
  • my major problem is with why i was unable to pass spritearray[i] = Ncardinal.. into the function and retrieve its elements inside the function like .lat, .lon ? sorry to say i just created a example code to explain my problem in programmatical way.. Nina scholz – rajesh Dec 10 '15 at 11:04
  • Your parameters are being passed, that's all fine, but you needed to define the `position` property before adding sub-properties to it... see my answer with a working snippet. – Shomz Dec 10 '15 at 11:05
  • Possible duplicate of [How to loop through an array containing objects and access their properties](http://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties) – Nikita U. Dec 10 '15 at 11:08

1 Answers1

0

You need to define this.position before adding properties to it.


Here's a working version that outputs sprite positions onto the console:

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);
}
Shomz
  • 37,421
  • 4
  • 57
  • 85