Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Javascript behavior - js object

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

like image 756
NaN Avatar asked Nov 04 '22 17:11

NaN


1 Answers

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".

like image 179
nneonneo Avatar answered Nov 15 '22 07:11

nneonneo