Javascript, console.log prints prints object, but property is undefined

1.7k views Asked by At

And I have a function that reads in level data. This is the snippet in question; actors is an array and I'm looping over it until i find an actor of type player.

function Level(plan) {
   //Cut snippet..........
    this.player = this.actors.filter(function(actor) {
        return actor.type == "player";
    });

    console.log(this.player);
//................  
}

The player object,

function Player(pos) {
    this.pos = pos
    this.size = new Vector(0.8, 1.5);
    this.speed = new Vector(0, 0);
}
Player.prototype = new Actor();
Player.prototype.type = "player"

The issue is that in the console, the

console.log(this.player)

will show all the correct details, but when i try to log the position for example

console.log(this.player.pos)

I get undefined. Its a simple program, I'm not using ajax or anything. Thought it might be do with execution order, can someone explain this to me and a solution? If it is todo with execution order, an explanation would be much appreciated.

Thank you very much, Rainy

2

There are 2 answers

0
Fadil Mamedov On BEST ANSWER

You get undefined because when you filter your actor array, you get a new array as a result. So console.log(this.player) outputs an array, not a single object.

You need to get the first element of the array this.player to output its pos property.

Something like this:

if(this.player.length > 0) 
    console.log(this.player[0].pos);
0
Miguel Mota On

Use reduce instead of filter for a single player.

  this.player = this.actors.reduce(function(current, actor) {
      return actor.type === 'player' ? actor : current;
  });