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 ```
18
19 ### Subsets
20
21 #### Immutable
22
23 ```bash
24 list.slice(0,1)         // → [a        ]
25 list.slice(1)           // → [  b,c,d,e]
26 list.slice(1,2)         // → [  b      ]
27 ```
28
29 #### Mutative
30
31 ```bash
32 re = list.splice(1)     // re = [b,c,d,e]  list == [a]
33 re = list.splice(1,2)   // re = [b,c]      list == [a,d,e]
34 ```
35
36 ### Adding items
37
38 #### Immutable
39
40 ```bash
41 list.concat([X,Y])      // → [_,_,_,_,_,X,Y]
42 ```
43
44 #### Mutative
45
46 ```bash
47 list.push(X)            // list == [_,_,_,_,_,X]
48 list.unshift(X)         // list == [X,_,_,_,_,_]
49 list.splice(2, 0, X)    // list == [_,_,X,_,_,_]
50 ```
51
52 ### Inserting
53
54 ```bash
55 // after -- [_,_,REF,NEW,_,_]
56 list.splice(list.indexOf(REF)+1, 0, NEW))
57 ```
58
59 ```bash
60 // before -- [_,_,NEW,REF,_,_]
61 list.splice(list.indexOf(REF), 0, NEW))
62 ```
63
64 ### Replace items
65
66 ```bash
67 list.splice(2, 1, X)    // list == [a,b,X,d,e]
68 ```
69
70 ### Removing items
71
72 ```bash
73 list.pop()              // → e    list == [a,b,c,d]
74 list.shift()            // → a    list == [b,c,d,e]
75 list.splice(2, 1)       // → [c]  list == [a,b,d,e]
76 ```
77
78 ### Iterables
79
80 ```bash
81 .filter(n => ...) => array
82 ```
83
84 ```bash
85 .find(n => ...)  // es6
86 .findIndex(...)  // es6
87 ```
88
89 ```bash
90 .every(n => ...) => Boolean // ie9+
91 .some(n => ..) => Boolean   // ie9+
92 ```
93
94 ```bash
95 .map(n => ...)   // ie9+
96 .reduce((total, n) => total) // ie9+
97 .reduceRight(...)
98 ```