LEARNING JAVASCRIPT - Trang 73

Arrays

In JavaScript, arrays are a special type of object. Unlike regular objects, array contents

have a natural order (element 0 will always come before element 1), and keys are

numeric and sequential. Arrays support a number of useful methods that make this

data type an extremely powerful way to express information, which we will cover in

Chapter 8

.

If you’re coming from other languages, you’ll find that arrays in JavaScript are some‐

thing of a hybrid of the efficient, indexed arrays of C and more powerful dynamic

arrays and linked lists. Arrays in JavaScript have the following properties:

• Array size is not fixed; you can add or remove elements at any time.
• Arrays are not homogeneous; each individual element can be of any type.
• Arrays are zero-based. That is, the first element in the array is element 0.

Because arrays are special types of objects with some extra func‐

tionality, you can assign non-numeric (or fractional or negative)

keys to an array. While this is possible, it contradicts the intended

purpose of arrays, can lead to confusing behavior and difficult-to-

diagnose bugs, and is best avoided.

To create an array literal in JavaScript, use square brackets, with the elements of the

array separated by commas:

const

a1

=

[

1

,

2

,

3

,

4

];

// array containing numbers

const

a2

=

[

1

,

'two'

,

3

,

null

];

// array containing mixed types

const

a3

=

[

// array on multiple lines

"What the hammer? What the chain?"

,

"In what furnace was thy brain?"

,

"What the anvil? What dread grasp"

,

"Dare its deadly terrors clasp?"

,

];

const

a4

=

[

// array containing objects

{

name

:

"Ruby"

,

hardness

:

9

},

{

name

:

"Diamond"

,

hardness

:

10

},

{

name

:

"Topaz"

,

hardness

:

8

},

];

const

a5

=

[

// array containing arrays

[

1

,

3

,

5

],

[

2

,

4

,

6

],

];

Arrays have a property

length

, which returns the number of elements in the array:

const

arr

=

[

'a'

,

'b'

,

'c'

];

arr

.

length

;

// 3

Arrays | 49