简体   繁体   中英

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

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

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);

Use reduce instead of filter for a single player.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM