function
() {
return
"arrays can contain functions too"
; },
"three"
,
];
// accessing elements
arr1
[
0
];
// 1
arr1
[
2
];
// 3
arr3
[
1
];
// ["one", 2, "three"]
arr4
[
1
][
0
];
// { name: "Susan", type: "object" }
// array length
arr1
.
length
;
// 3
arr4
.
length
;
// 5
arr4
[
1
].
length
;
// 2
// increasing array size
arr1
[
4
]
=
5
;
arr1
;
// [1, 2, 3, undefined, 5]
arr1
.
length
;
// 5
// accessing (not assigning) an index larger than the array
// does *not* change the size of the array
arr2
[
10
];
// undefined
arr2
.
length
;
// 3
// Array constructor (rarely used)
const
arr5
=
new
Array
();
// empty array
const
arr6
=
new
Array
(
1
,
2
,
3
);
// [1, 2, 3]
const
arr7
=
new
Array
(
2
);
// array of length 2 (all elements undefined)
const
arr8
=
new
Array
(
"2"
);
// ["2"]
Array Content Manipulation
Before we get into the exciting methods, let’s first consider the (very useful) methods
for manipulating arrays. One aspect of array methods that is unfortunately confusing
is the difference between methods that modify the array “in place” and those that
return a new array. There’s no convention, and this is just one of these things you
have to memorize (for example, that
push
modifies an array in place but
concat
returns a new array).
132 | Chapter 8: Arrays and Array Processing