HTML and CSS Reference
In-Depth Information
To access the object, you can use either dot or bracket notation:
> player['position'].x
> player['position']['y']
Note that when using bracket notation, you need to enclose the key in quotes. If you don't do this, then the key
will instead be treated like a variable:
> x = "unknownProperty";
> player['position'][x]
This code returns undefined , because the interpreter can't find player['position']['unknownProperty'] . As a
side note, you should minimize use of bracket notation whenever possible. Dot notation uses fewer bytes to represent
the same thing and can be more effectively minified over the wire (for more information, see the section “Inheritance
the JavaScript Way”).
Arrays act similarly to other languages you may be familiar with:
> x = [1, 10, 14, "15"]
[1, 10, 14, "15"]
> x[0]
> x[3]
> x.length
> x.push(20, "I'm last!")
> x
[1, 10, 14, "15", 20, "I'm last!"]
As you can see, arrays are heterogenous, meaning that you can have arbitrary types in a single array. Note that
this is a bad idea; the internal representation for heterogenous arrays causes some serious performance headaches.
Always try to keep a single type in a given array.
Arrays have a number of convenience functions as well, such as push , pop , and slice . I'm not going to go into
much detail on these here. To learn more about them, check out the coverage of the Array object by the Mozilla
Developer Network (MDN) (
Global_Objects/Array ).
I do, however, want to sound a note of caution regarding the memory performance of these convenience
functions. Most, if not all, act by allocating an entirely new array from the heap rather than modifying things in place.
In general, garbage collection and memory management are going to be huge performance concerns in
JavaScript, so you want to avoid allocating new arrays and causing object churn as much as possible.
Search WWH ::

Custom Search