Вопрос

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 there's absolutely no chance that it'll be null, a blank string, zero, or any other 'falsey' JS value you can just do

if(room.exits[direction]) { // go that way }
else {print "you can't go that way!"}

I also did a speed test against the 'in' operator that p.s.w.g posted as an answer because it never really occurred to me to use it. I found some interesting results that you should consider if you're running this in any kind of loop at any point.

http://jsperf.com/test-in-operator-vs-if

It seems that the "in" operator is SIGNIFICANTLY slower on IE and Chrome, but on Firefox it's almost twice as fast.

you should do:

if (room.exits.south) {// go that way}
else {print "you can't go that way!"}

that's it.

When "south" is undefined (or when it is zero or empty string or literal false), the predicate evaluates to false.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top