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.,.lengthand ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access