LEARNING JAVASCRIPT - Trang 155

CHAPTER 8

Arrays and Array Processing

JavaScript’s array methods are among my favorite features of the language. So many

programming problems involve the manipulation of collections of data, and fluency

with JavaScript’s array methods will make that easy. Getting comfortable with these

methods is also a great way to attain the next level of JavaScript mastery.

A Review of Arrays

Before we dive in, let’s remind ourselves of the basics of arrays. Arrays (unlike

objects) are inherently ordered, with zero-based numeric indices. Arrays in JavaScript

can be nonhomogeneous, meaning the elements in an array do not need to be the

same type (it follows from this that arrays can have other arrays as elements, or

objects). Literal arrays are constructed with square brackets, and the same square

brackets are used to access elements by index. Every array has a

length

property,

which tells you how many elements are in the array. Assigning to an index that’s

larger than the array will automatically make the array larger, with unused indexes

getting the value

undefined

. You can also use the

Array

constructor to create arrays,

though this is seldom necessary. Make sure all of the following makes sense to you

before you proceed:

// array literals

const

arr1

=

[

1

,

2

,

3

];

// array of numbers

const

arr2

=

[

"one"

,

2

,

"three"

];

// nonhomogeneous array

const

arr3

=

[[

1

,

2

,

3

], [

"one"

,

2

,

"three"

]];

// array containing arrays

const

arr4

=

[

// nonhomogeneous array

{

name

:

"Fred"

,

type

:

"object"

,

luckyNumbers

=

[

5

,

7

,

13

] },

[
{

name

:

"Susan"

,

type

:

"object"

},

{

name

:

"Anthony"

,

type

:

"object"

},

],

1

,

131

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.