forked from HackYourFuture-CPH/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjects.js
More file actions
111 lines (82 loc) · 1.9 KB
/
objects.js
File metadata and controls
111 lines (82 loc) · 1.9 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// one way to have multiple data about a student is with an array
// for each piece of data
var studentNames = [
'Fowad',
'Emil',
'Zoey'
]
var studentAges = [
32,
25,
28
]
console.log(studentNames)
console.log(studentAges)
// Another, more ergonomic way is with objects
var students = [
{ name: 'Fowad', age: 32 },
{ name: 'Emil', age: 25, teacher: true },
{ name: 'Zoey', age: 28 }
]
console.log(students)
// We can access properties with `.`
console.log(students[0].name)
// One object that we have seen before
var Math = {
random: function () {
return 42
},
round: function (x) {
}
}
var person = {
name: 'Emil',
age: 25,
role: 'Teacher',
classes: ['Javascript 1', 'Javascript 2'],
hobbies: {
favourite: 'computers',
sports: 'running to class'
}
}
console.log(person)
// Add new property
person.lastname = 'Bay'
console.log(person)
delete person.lastname
console.log(person)
console.log(person.hobbies.favourite)
console.log({ favourite: 'computers', sports: 'running to class' }.favourite)
'Hello world'.replace('Hello', 'Hej').replace('world', 'verden')
function graduatedClass (student, className) {
if (student.classes.includes(className)) return 'Error'
student.classes.push(className)
}
console.log(person)
graduatedClass(person, 'HTML')
console.log(person)
graduatedClass(person, 'HTML')
var newPerson = {
name: '',
age: ''
}
function addStudent(student) {
if (student.name == null && typeof student.name === 'string') return 'Error'
if (student.age == null) return 'Error'
students.push(student)
}
addStudent({ name: 'Rahim' })
console.log(students)
// ways to access properties
person.name
person['name']
var prop = 'name'
person[prop]
person['name'] = 'Maria'
person[0] = 'Hello world'
console.log(person)
function pick (obj, prop, defaultValue) {
if (obj[prop]) return obj[prop]
return defaultValue
}
pick(person, 'age', 'Unknown')