Chapter 9. Array()
Conceptual Overview of Using Array() Objects
An array is an ordered list of values, typically created with the intention of looping through numerically indexed values, beginning with the index zero. What you need to know is that arrays are numerically ordered sets, versus objects, which have property names associated with values in non-numeric order. Essentially, arrays use numbers as a lookup key, while objects have user-defined property names. JavaScript does not have true associative arrays, but objects can be used to achieve the functionality of associate arrays.
Below, I store four strings in myArray
that I can access using a numeric index.
I compare and contrast it to an object-literal mimicking an associative
array.
<!DOCTYPE html><html lang="en"><body><script> var myArray = ['blue', 'green', 'orange', 'red']; console.log(myArray[0]); // logs blue using 0 index to access string in myArray // versus var myObject = { // a.k.a. associative array/hash, known as an object in JavaScript 'blue': 'blue', 'green': 'green', 'orange': 'orange', 'red': 'red' }; console.log(myObject['blue']); // logs blue </script></body></html>
Notes
Arrays can hold any type of values, and these values can be updated or deleted at any time.
If you need a “hash” (a.k.a. associative array), an object is the closest solution.
An
Array()
is just a special type ofObject()
. That is,Array()
instances are basicallyObject()
instances with a couple of extra functions (e.g.,.length
and ...
Get JavaScript Enlightenment now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.