Comportamiento extraño de Javascript - objeto js
Frecuentes
Visto 108 veces
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
2 Respuestas
2
Tenga en cuenta que console.log(current_val);
salidas "true"
to the console. Since console.log
doesn't print quotes, it must be the case that current_val
contiene '"true"'
, que no es lo mismo que "true"
.
Respondido 28 ago 12, 08:08
0
Its because of the fact that true is not evaluated to string in the last statement.
Respondido 28 ago 12, 08:08
why not? typeof returns string?! ... How can I cast it to one? console.log(transitions[attr][String(current_val)]);
no funciona. - Yaya
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas javascript boolean javascript-objects or haz tu propia pregunta.
If
console.log(current_val);
produce"true"
entonces parececurrent_val
debe configurarse para'"true"'
, Desdeconsole.log
should not print quotes. - nneonneoFunciona bien aquí. Can you reproduce your problem in a fiddle? - Some Guy
Not sure, but using reserved words like that is asking for trouble ;) Still a good question though - Asciiom
@nneonneo Smart. You should submit that as an answer. - Some Guy
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
para la última fila) - Yoshi