-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrays.js
More file actions
85 lines (59 loc) · 1.29 KB
/
arrays.js
File metadata and controls
85 lines (59 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* Literals
*/
var empty = [];
var numbers = [
'zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine'
];
empty[1] // undefined
numbers[1] // 'one'
empty.length // 0
numbers.length // 10
/*
* Length
*/
var myArray = [];
myArray.length // 0
myArray[1000000] = true;
myArray.length // 1000001
// myArray contains one property.
numbers.length = 3;
// numbers is ['zero', 'one', 'two']
numbers.push('go');
// numbers is ['zero', 'one', 'two', 'go']
/*
* Delete
*/
numbers.splice(2, 1);
// numbers is ['zero', 'one', 'go']
/*
* Enumeration
*/
for (var i = 0; i < numbers.length; i += 1) {
console.log(numbers[i]);
}
/*
* Methods
*/
numbers.forEach(function (element) {
console.log(element);
});
// Create an array of numbers.
var data = [4, 8, 15, 16, 23, 42];
// Create a function for squaring numbers.
var square = function (a) {
return a * a;
};
var squares = data.map(square);
// squares is [16, 64, 225, 256, 529, 1764]
// Invoke the data's reduce method, passing in the
// add function.
var sum = data.reduce(function (a, b) {
return a + b;
}, 0); // sum is 108
// Invoke the reduce method again, this time passing
// in the multiply function.
var product = data.reduce(function (a, b) {
return a * b;
}, 1); // product is 7418880