Skip to content

Commit 3823698

Browse files
committed
Merge pull request jquery#88 from ddprrt/master
Rework `javascript-101/arrays.md`
2 parents db232e9 + 458b205 commit 3823698

File tree

1 file changed

+223
-18
lines changed

1 file changed

+223
-18
lines changed

content/javascript-101/arrays.md

Lines changed: 223 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,242 @@
11
---
22
title: Arrays
3-
attribution: jQuery Fundamentals
3+
attribution:
4+
- jQuery Fundamentals
5+
- Stefan Baumgartner
6+
github: ddprrt
47
---
5-
Arrays are zero-indexed lists of values. They are a handy way to store a set of
8+
Arrays are zero-indexed, ordered lists of values. They are a handy way to store a set of
69
related items of the same type (such as strings), though in reality, an array
710
can include multiple types of items, including other arrays.
811

12+
To create an array you can either use the object constructor or the literal declaration,
13+
by assigning your variable a list of values right after the declaration.
14+
915
<javascript caption="A simple array">
10-
var myArray = [ 'hello', 'world' ];
16+
var myArray1 = new Array( 'hello', 'world' ); // with constructor
17+
var myArray2 = [ 'hello', 'world' ]; // literal declaration, the preferred way
1118
</javascript>
1219

20+
The literal declaration is preferred, see the
21+
[Google Coding Guidelines](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Array_and_Object_literals)
22+
for more information.
23+
24+
If you don't know your values yet, it is also possible to declare an empty Array, and
25+
add elements either through functions or through accessing by index:
26+
27+
<javascript caption="Creating empty arrays and adding values">
28+
var myArray = [];
29+
30+
myArray.push('hello'); // adds 'hello' on index 0
31+
myArray.push('world'); // adds 'world' on index 1
32+
myArray[2] = '!'; // adds '!' on index 2
33+
</javascript>
34+
35+
'push' is a function which adds an element on the end of the array and expands the array
36+
respectively. You also can directly add items by index. Missing indices will be filled
37+
with 'undefined';
38+
39+
<javascript caption="Leaving indices">
40+
var myArray = [];
41+
42+
myArray[0] = 'hello';
43+
myArray[1] = 'world';
44+
myArray[3] = '!';
45+
46+
console.log(myArray); // logs ['hello', 'world', undefined, '!'];
47+
</javascript>
48+
49+
So 'push' is far more safe, especially if you don't know the size of your
50+
array yet. With the index you not only assign values to array items, but also
51+
access those.
52+
1353
<javascript caption="Accessing array items by index">
14-
var myArray = [ 'hello', 'world', 'foo', 'bar' ];
15-
console.log(myArray[3]); // logs 'bar'
54+
var myArray = [ 'hello', 'world', '!'];
55+
console.log(myArray[2]); // logs '!'
56+
</javascript>
57+
58+
### Array methods and properties
59+
60+
## length
61+
62+
The 'length' property is used to know the amount of items in your array.
63+
64+
<javascript caption="Length of an array">
65+
var myArray = [ 'hello', 'world', '!'];
66+
console.log(myArray.length); // logs 3
67+
</javascript>
68+
69+
You will need the length property for looping through an array:
70+
71+
<javascript caption="For loops and arrays - a classic">
72+
var myArray = ['hello', 'world', '!'];
73+
for(var i = 0; i < myArray.length; i = i + 1) {
74+
console.log(myArray[i]);
75+
}
76+
</javascript>
77+
78+
Except when you are using for ... in loops:
79+
80+
<javascript caption"For loops and arrays - alternate method">
81+
var myArray = ['hello', 'world', '!'];
82+
for(var i in myArray) {
83+
console.log(myArray[i]);
84+
}
85+
</javascript>
86+
87+
## concat
88+
89+
With 'concat', you can concatenate two or more arrays
90+
91+
<javascript caption="Concatenating Arrays">
92+
var myArray = [2, 3, 4];
93+
var myOtherArray = [5, 6, 7];
94+
var wholeArray = myArray.concat(myOtherArray); // [2, 3, 4, 5, 6, 7]
95+
</javascript>
96+
97+
## join
98+
99+
'join' creates a string representation of your array. It's parameter is as string
100+
which works as a seperator between elements (default is a comma);
101+
102+
<javascript caption="Joining elements">
103+
var myArray = ['hello', 'world', '!'];
104+
console.log(myArray.join(' ')); // logs "hello world !";
105+
console.log(myArray.join()); // logs "hello,world,!"
106+
console.log(myArray.join('')); // logs "helloworld!"
107+
console.log(myArray.join('!!')) // logs "hello!!world!!!!!";
108+
</javascript>
109+
110+
## pop
111+
112+
'pop' removes the last element of an array. It is the opposite method to 'push'
113+
114+
<javascript caption="pushing and popping">
115+
var myArray = [];
116+
myArray.push(0); // [ 0 ]
117+
myArray.push(2); // [ 0 , 2 ]
118+
myArray.push(7); // [ 0 , 2 , 7 ]
119+
myArray.pop(); // [ 0 , 2 ]
120+
</javascript>
121+
122+
## reverse
123+
124+
As the name suggests, the elements of the array are in reverse order after calling
125+
this method
126+
127+
<javascript caption="reverse">
128+
var myArray = [ 'world' , 'hello' ];
129+
myArray.reverse(); // [ 'hello', 'world' ]
130+
</javascript>
131+
132+
## shift
133+
134+
Removes the first element of an array. With 'pop' and 'shift' you can recreate the
135+
method of a [queue](http://en.wikipedia.org/wiki/Queue_(data_structure))
136+
137+
<javascript caption="queue with shift() and pop()">
138+
var myArray = [];
139+
myArray.push(0); // [ 0 ]
140+
myArray.push(2); // [ 0 , 2 ]
141+
myArray.push(7); // [ 0 , 2 , 7 ]
142+
myArray.shift(); // [ 2 , 7 ]
143+
</javascript>
144+
145+
## slice
146+
147+
Extracts a part of the array and returns them in a new one. This method takes one
148+
parameter, which is the starting index.
149+
150+
<javascript caption="slicing">
151+
var myArray = [1, 2, 3, 4, 5, 6, 7, 8];
152+
var newArray = myArray.slice(3);
153+
154+
console.log(myArray); // [1, 2, 3, 4, 5, 6, 7, 8]
155+
console.log(newArray); // [4, 5, 6, 7, 8]
156+
</javascript>
157+
158+
## splice
159+
160+
Removes a certain amount of elements and adds new ones at the given index. It takes
161+
at least 3 parameters
162+
163+
<javascript caption="splice method">
164+
myArray.splice(idx, len, values, ...);
16165
</javascript>
17166

18-
<javascript caption="Testing the size of an array">
19-
var myArray = [ 'hello', 'world' ];
20-
console.log(myArray.length); // logs 2
167+
* idx = the starting index
168+
* len = the number of elements to remove
169+
* values = the values which should be inserted at idx
170+
171+
For example:
172+
173+
<javascript caption="splice example">
174+
var myArray = [0, 7, 8, 5];
175+
myArray.splice(1, 2, 1, 2, 3, 4);
176+
console.log(myArray); // [0, 1, 2, 3, 4, 5]
21177
</javascript>
22178

23-
<javascript caption="Changing the value of an array item">
24-
var myArray = [ 'hello', 'world' ];
25-
myArray[1] = 'changed'; // myArray is now now ['hello', 'changed']
179+
## sort
180+
181+
Sorts an array. It takes one parameter, which is a comparing function. If this function is not
182+
given, the array is sorted ascending
183+
184+
<javascript caption="sorting without comparing function">
185+
var myArray = [3, 4, 6, 1];
186+
myArray.sort(); // 1, 3, 4, 6
26187
</javascript>
27188

28-
<javascript caption="Adding elements to an array">
29-
var myArray = [ 'hello', 'world' ];
30-
myArray.push('new'); // myArray is now ['hello', 'world', 'new']
189+
<javascript caption="sorting with comparing function">
190+
function descending(a, b) {
191+
return b - a;
192+
}
193+
var myArray = [3, 4, 6, 1];
194+
myArray.sort(descending); // [6, 4, 3, 1]
31195
</javascript>
32196

33-
<javascript caption="Working with arrays">
34-
var myArray = [ 'h', 'e', 'l', 'l', 'o' ];
35-
var myString = myArray.join(''); // myString = 'hello'
36-
var mySplit = myString.split(''); // mySPlit = [ 'h', 'e', 'l', 'l', 'o' ]
197+
The return value of descending (for this example) is important. If the return value is
198+
less than zero, the index of a is before b, and if it is greater than zero it's vice-versa.
199+
If the return value is zero, the elements index is equal.
200+
201+
## unshift
202+
203+
Inserts an element at the first position of the array
204+
205+
<javascript caption="unshift">
206+
var myArray = [];
207+
myArray.unshift(0); // [ 0 ]
208+
myArray.unshift(2); // [ 2 , 0 ]
209+
myArray.unshift(7); // [ 7 , 2 , 0 ]
210+
</javascript>
211+
212+
## forEach
213+
214+
In modern browsers, like Chrome, Firefox and Internet Explorer 9 it is possible to traverse
215+
through arrays by a so called 'forEach' method, where you pass a function which is called
216+
for each element in your array.
217+
218+
The function takes up to three arguments:
219+
* element - The element itself
220+
* index - The index of this element in the array
221+
* array - The array itself
222+
223+
All of the are optional, but you will need at least the 'element' parameter in most cases.
224+
225+
<javascript caption="native forEach">
226+
function printElement(elem) {
227+
console.log(elem);
228+
}
229+
230+
function printElementAndIndex(elem, index) {
231+
console.log("Index " + index + ": " + elem);
232+
}
233+
234+
function negateElement(elem, index, array) {
235+
array[index] = -elem;
236+
}
237+
238+
myArray = [1, 2, 3, 4, 5];
239+
myArray.forEach(printElement); //prints all elements to the console
240+
myArray.forEach(printElementAndIndex); //prints "Index 0: 1" "Index 1: 2" "Index 2: 3" ...
241+
myArray.forEach(negateElement); // myArray is now [-1, -2, -3, -4, -5]
37242
</javascript>

0 commit comments

Comments
 (0)