In the text adventure I am making, my object literals for the rooms look like this:
room : {
  // some info,
  exits : {
    north : -1,
    east : "house",
    south : "forest",
    west : -1
  }
}
and in my function to move around it says:
if (room["exits"][direction] !== -1) {// go that way}
else {print "you can't go that way!"}
now I want to save space by just testing if the key for the relevant direction exits in the object. so the literals will go:
room : {
  // some info,
  exits : {
    east : "house",
    south : "forest"
  }
}
... what should my if statement look like? what is the 'proper' way to ascertain if a given key-name exits in the object?
You can use the in operator:
if (direction in room.exits) {
    // go that way
} else { 
    console.log("you can't go that way!");
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With