Suppose I have an object
obj = {
a : 1
}
I'm able to access property a
via obj["a"]
but I'm also able to access it via obj[["a"]]
. How is that possible?
On each iteration, we assign the array value as a key in the object and return the new value of the accumulator variable. We initialized each key to an empty string, however you can assign whatever value suits your use case. The object will contain all of the array's elements as keys after the last iteration.
So if you want to access a property named 2 or John Doe, you must use square brackets: value[2] or value["John Doe"] . The elements in an array are stored as the array's properties, using numbers as property names.
Array properties also exist. These are properties that accept an index, just as an array does. The index can be one-dimensional, or multi-dimensional. In difference with normal (static or dynamic) arrays, the index of an array property doesn't have to be an ordinal type, but can be any type.
Properties are made up of key : value pairs. We may see the term property used to indicate a key, but on the whole we may think of a property as having both a name and a value. This of course differs from key, since key is just a name.
Object keys are always strings (or, rarely, symbols). When you do
obj[<expression>]
the interpreter will try to turn expression
into a valid key, if it isn't one already. In this case, turning ["a"]
into a string results in "a"
, so both obj["a"]
and obj[["a"]]
work.
(When an array is implicitly turned into a primitive, like here, it gets .join
ed by a comma, and ["a"].join(',') === "a"
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With