Tuesday 15 June 2010

May I use numeric in a javascript object? -


It is my understanding that the keys of objects are always string, however, I believe that the numerical values ​​will be translated into strings if the key , It will not be any kind of prohibited value type. Since we do not use quotation marks around string keys, writing content like this:

  {a: "a_value", b: "b_value", [...]}   

... I thought the stuff could be easy to read:

  {1: "first_name", 4: "whatever" , [...]}   

So my question is: Is it really bad behavior is considered to use numerical values ​​in the form of keys, or am I less Less or less I could Nationality?

Thank you.

You are right that the name of the property should be string, but the conversion is done for you. That is, o = {1: "test" "} is the same as o = {" 1 ":" test "} . Similarly, o [ 45] and o [45] = "Hello" both . , change the property name for you.

This is a Quick display is where I have overridden toString () to make it clear:

  var o = {xyz: 100, toString: function () {console ("Someone stradded me"); Return "Ow";}} var x = {}; x [o] = "test"; // Console says, "Someone was tricked" console.log (x ["Ooo"]); // Console is called "Test"; console.log (x [o]); // console says, "someone stradded me", then "test"   

O is used as a property, it is an indication that it is used in the string using o.toString () , so that the numeric key Using is not a problem. Actually, you can check out ["hi", "ol", "father"] ["1"] and see that it is "[hi", " Ol "," father "] [1]`

No comments:

Post a Comment