HTML and CSS Reference
In-Depth Information
To access the object, you can use either dot or bracket notation:
> player.health
10
> player['position'].x
325
> player['position']['y']
210
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";
"unknownProperty"
> player['position'][x]
undefined
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
Arrays act similarly to other languages you may be familiar with:
> x = [1, 10, 14, "15"]
[1, 10, 14, "15"]
> x[0]
1
> x[3]
"15"
> x.length
4
> x.push(20, "I'm last!")
Undefined
> 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) ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/
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