5

I want to code some sort of state machine with different transitions. But something strange happens, when I want to select an item.

var transitions = {
    "on": {
        "false":"true",
        "true":"false"
    }
}

The last two lines are very interresting - the same index, first hardcoded and the second stored within a variable. Why does the first return the right result (false) and the other undefined?

console.log(attr);                             // on
console.log(transitions[attr]);                // Object { false="true, true="false" }
console.log(current_val);                      // "true"
console.log(typeof current_val);               // string
console.log(transitions[attr]["true"]);        // false
console.log(transitions[attr][current_val]);   // undefined

info: I use FF 14.0.1

5
  • 4
    If console.log(current_val); produces "true" then it seems current_val must be set to '"true"', since console.log should not print quotes.
    – nneonneo
    Aug 28, 2012 at 7:34
  • Works fine here. Can you reproduce your problem in a fiddle?
    – Some Guy
    Aug 28, 2012 at 7:34
  • Not sure, but using reserved words like that is asking for trouble ;) Still a good question though
    – Asciiom
    Aug 28, 2012 at 7:34
  • 1
    @nneonneo Smart. You should submit that as an answer.
    – Some Guy
    Aug 28, 2012 at 7:35
  • 1
    interesting sidenote (regarding chrome): running the code in an html page (or jsfiddle) gives the desired output, running it completely in the console gives the described output (e.g. undefined for the last row)
    – Yoshi
    Aug 28, 2012 at 7:55

2 Answers 2

2

Note that console.log(current_val); outputs "true" to the console. Since console.log doesn't print quotes, it must be the case that current_val contains '"true"', which isn't the same as "true".

0

Its because of the fact that true is not evaluated to string in the last statement.

1
  • why not? typeof returns string?! ... How can I cast it to one? console.log(transitions[attr][String(current_val)]); doesn't work.
    – NaN
    Aug 28, 2012 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.