You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: notes/javascript/datatypes/arrays.md
+11-9Lines changed: 11 additions & 9 deletions
Original file line number
Diff line number
Diff line change
@@ -31,13 +31,9 @@ Like other languages, individual array values can be accessed by their index. Ar
31
31
var arr = ["a", "b", "c", "d"]
32
32
33
33
arr[0] //> "a"
34
-
35
34
arr[1] //> "b"
36
-
37
35
arr[2] //> "c"
38
-
39
36
arr[3] //> "d"
40
-
41
37
arr[4] //> undefined
42
38
````
43
39
@@ -58,11 +54,8 @@ It is possible to get the index value of any item in the array. In the event the
58
54
var arr = ["a", "b", "c", "b", "a"]
59
55
60
56
arr.indexOf("a") //> 0
61
-
62
57
arr.indexOf("b") //> 1
63
-
64
58
arr.indexOf("c") //> 2
65
-
66
59
arr.indexOf("z") //> -1 (applies to any item not found in the array)
67
60
````
68
61
@@ -72,11 +65,21 @@ Counting the number of items in an array:
72
65
73
66
````js
74
67
var arr = ["a", "b", "c", "d"]
68
+
75
69
arr.length//> 4
76
70
````
77
71
78
72
79
-
Checking to see if an item is (or is not) in the array:
73
+
One trick for dynamically accessing the last item in an array (no matter how many there are) is to leverage the length of the array and subtract one, to arrive at the index of the last item:
74
+
75
+
```js
76
+
var arr = ["a", "b", "c", "d"]
77
+
78
+
arr[arr.length-1] //> "d"
79
+
```
80
+
81
+
82
+
Checking to see if an item is in the array, or not:
80
83
81
84
````js
82
85
var arr = ["a", "b", "c", "d"]
@@ -95,7 +98,6 @@ Adding an item to the end of an array:
0 commit comments