OSDN Git Service

Regular updates
[twpd/master.git] / js-array.md
1 ---
2 title: JavaScript Arrays
3 category: JavaScript
4 layout: 2017/sheet
5 ---
6
7 ### Arrays
8
9 ```bash
10 list = [a,b,c,d,e]
11 ```
12 {: .-setup}
13
14 ```bash
15 list[1]                 // → b
16 list.indexOf(b)         // → 1
17 list.lastIndexOf(b)     // → 1
18 list.includes(b)        // → true
19 ```
20
21 ### Subsets
22
23 #### Immutable
24
25 ```bash
26 list.slice(0,1)         // → [a        ]
27 list.slice(1)           // → [  b,c,d,e]
28 list.slice(1,2)         // → [  b      ]
29 ```
30
31 #### Mutative
32
33 ```bash
34 re = list.splice(1)     // re = [b,c,d,e]  list == [a]
35 re = list.splice(1,2)   // re = [b,c]      list == [a,d,e]
36 ```
37
38 ### Adding items
39
40 #### Immutable
41
42 ```bash
43 list.concat([X,Y])      // → [_,_,_,_,_,X,Y]
44 ```
45
46 #### Mutative
47
48 ```bash
49 list.push(X)            // list == [_,_,_,_,_,X]
50 list.unshift(X)         // list == [X,_,_,_,_,_]
51 list.splice(2, 0, X)    // list == [_,_,X,_,_,_]
52 ```
53
54 ### Inserting
55
56 ```bash
57 // after -- [_,_,REF,NEW,_,_]
58 list.splice(list.indexOf(REF)+1, 0, NEW))
59 ```
60
61 ```bash
62 // before -- [_,_,NEW,REF,_,_]
63 list.splice(list.indexOf(REF), 0, NEW))
64 ```
65
66 ### Replace items
67
68 ```bash
69 list.splice(2, 1, X)    // list == [a,b,X,d,e]
70 ```
71
72 ### Removing items
73
74 ```bash
75 list.pop()              // → e    list == [a,b,c,d]
76 list.shift()            // → a    list == [b,c,d,e]
77 list.splice(2, 1)       // → [c]  list == [a,b,d,e]
78 ```
79
80 ### Iterables
81
82 ```bash
83 .filter(n => ...) => array
84 ```
85
86 ```bash
87 .forEach(n => ...)
88 ```
89
90 ```bash
91 .find(n => ...)  // es6
92 .findIndex(...)  // es6
93 ```
94
95 ```bash
96 .every(n => ...) => Boolean // ie9+
97 .some(n => ..) => Boolean   // ie9+
98 ```
99
100 ```bash
101 .map(n => ...)   // ie9+
102 .reduce((total, n) => total) // ie9+
103 .reduceRight(...)
104 ```