(pseudo) array accessors with arbitrary index, where index is property name as string
or
map or directory (object) accessors with key, where key is property name as string
After all, it is just syntax, and the interpreter knows what kind 'thing' it is that is in front of the square brackets:
either
a real Array object (w/ consecutive, numerically indexed series of - usually - adjacent storage slots - then the value in the brackets has to be a number
or
a real Object (w/ arbitrary 'indexed'/ named properties) - then the value in the brackets has to be a property name as string (see also JSON - JavaScript Object Notation - an object declaration in string form: oAsJSONString = '{"n":3,"s":"str"}' - see JSON.stringify(o)/.parse(oAsJsonString) - PS: also supporting arrays... )
Even though the Array is also an object... it is fundamentally different intrinsic to the implementation and behaves as such differently, even though it has similar looks and analogue functionality - as JSON shows.
On the other hand, you can think reverse:
o.n is the short form of o["n"]...
After all it is just a notation by convention and pure syntax - sugar or salt, what ever you like - that spices up the code... (hence it's name code, coding, codified meaning).
There is more of the CS Formal Languages theory/philosophy around this... like What are the real, realm specific differences between {n:3,s:"str"} and [3,"str"] and '{"n":3,"s":"str"}' ? ... may be at another post's time...
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
When you have an object with (named) properties -
var o = {n:3,s:"str"}
, think of the square bracketseither as
short form of getter and setter methods to access properties
n
ands
with the property name as string"n"
and"s"
:which you use as, for examples
that equals to
o["n"]; o["s"]="me";
or
or
After all, it is just syntax, and the interpreter knows what kind 'thing' it is that is in front of the square brackets:
either
or
oAsJSONString = '{"n":3,"s":"str"}'
- seeJSON.stringify(o)/.parse(oAsJsonString)
- PS: also supporting arrays... )Even though the Array is also an object... it is fundamentally different intrinsic to the implementation and behaves as such differently, even though it has similar looks and analogue functionality - as JSON shows.
On the other hand, you can think reverse:
o.n
is the short form ofo["n"]
...After all it is just a notation by convention and pure syntax - sugar or salt, what ever you like - that spices up the code... (hence it's name code, coding, codified meaning).
There is more of the CS Formal Languages theory/philosophy around this... like What are the real, realm specific differences between
{n:3,s:"str"}
and[3,"str"]
and'{"n":3,"s":"str"}'
? ... may be at another post's time...