-
Notifications
You must be signed in to change notification settings - Fork 0
/
loop.js
64 lines (62 loc) · 1.42 KB
/
loop.js
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
// loop through Object
//
const obj = {
name: "Alice",
age: 25,
city: "New York",
}
// use for..in loop
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(`${key}: ${obj[key]}`)
}
}
// use Object.keys() and forEach()
Object.keys(obj).forEach(key => {
console.log(`${key}: ${obj[key]}`)
})
// use Object.entries() and forEach()
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key}: ${value}`)
})
// use for..of with Object.entries()
for (let [key, value] of Object.entries(obj)) {
console.log(`${key}: ${value}`)
}
// loop through array
const arr = ["Alice", 25, "New York"]
// use for loop
for (let i = 0; i < arr.length; i++) {
console.log(`${i}: ${arr[i]}`)
}
// use for..of and entries()
for (let [index, value] of arr.entries()) {
console.log(`${index}: ${value}`)
}
// use map() method
arr.map((value, index) => console.log(`${index}: ${value}`))
// use filter() method
arr.filter((value, index) => {
if (typeof value === "string") {
console.log(`${index}: ${value}`)
}
})
// use reduce() method
const acc = arr.reduce((acc, value, index) => {
console.log(`${index}: ${value}`)
return acc
}, 0)
// loop through map
const map = new Map([
["name", "Alice"],
["age", 25],
["city", "New York"],
])
// for..of
for (let [k, v] of map) {
console.log(`${k}: ${v}`)
}
// for..each
map.forEach((v, k) => {
console.log(`${k}: ${v}`);
});