Skip to content

Commit 72f78bf

Browse files
committed
complete exercise 04 and guide of it
1 parent a861219 commit 72f78bf

File tree

5 files changed

+446
-3
lines changed

5 files changed

+446
-3
lines changed

04 - Array Cardio Day 1/README.md

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
# 04 Array Cardio 💪 指南
2+
3+
## 实现效果
4+
5+
这一部分主要是熟悉 Array 的几个基本方法,其中有两个(filter、map)是 ES5 定义的迭代方法,这些迭代方法都有一个特点,就是对数组的每一项都运行给定函数,根据使用的迭代方法的不同,有不同的返回结果。
6+
7+
文档给出了一个初始操作的 inventor 数组,基于这个数组可以练习一下 Array 的各个方法,请打开 HTML 后在 Console 面板中查看输出结果。
8+
9+
## 炫酷的调试技巧
10+
11+
在 Console 中我们常用到的可能是 `console.log()` ,但它还有一个很炫的输出,按照表格来输出,效果如下:
12+
13+
```js
14+
console.table(thing)
15+
```
16+
17+
![console.table()](https://cl.ly/0H023s441o2d/Image%202016-12-23%20at%203.51.50%20PM.png)
18+
19+
## 过程指南
20+
21+
1. 筛选 16 世纪出生的发明家
22+
2. 展示他们的姓和名
23+
3. 把他们按照年龄从大到小进行排序
24+
4. 计算所有的发明家加起来一共活了多少岁
25+
5. 按照他们活了多久来进行排序
26+
6. 筛选出一个网页里含有某个词语的标题
27+
7. 按照姓氏来对发明家进行排序
28+
8. 统计给出数组中各个物品的数量
29+
30+
## 相关知识
31+
32+
下面从简单的方法开始,后面有很多有意思的玩法。
33+
34+
### [filter](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
35+
36+
过滤操作,有点像 SQL 里面的 select 语句。筛出运行结果是 true 的组成数组返回。
37+
38+
````js
39+
const __fifteen = inventors.filter(function(inventor) {
40+
if (inventor.year >= 1500 && inventor.year < 1600 ) {
41+
return true;
42+
} else {
43+
return false;
44+
}
45+
});
46+
console.table(__fifteen);
47+
````
48+
49+
前面几篇已经提到过箭头函数,这里可以简化一下,用箭头函数来写,而且由于 if 语句的存在并不是必要的,可以写成下面这样:
50+
51+
````js
52+
const fifteen = inventors.filter(inventor =>(inventor.year >= 1500 && inventor.year < 1600));
53+
console.table(fifteen);
54+
````
55+
56+
### [map](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
57+
58+
map 形象的理解就是,把数组中的每个元素进行处理后,返回一个新的数组。
59+
60+
例子如下:
61+
62+
````js
63+
// 展示数组对象 inventors 里发明家的姓名
64+
const fullNames = inventors.map(inventor => inventor.first + ' ' + inventor.last);
65+
````
66+
67+
### [sort](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
68+
69+
默认情况下,`Array.prototype.sort()` 会将数组以字符串的形式进行升序排列(10 会排在 2 之前),但 sort 也可以接受一个函数作为参数。所以需要对数字大小排序时需要自己设定一个比较函数,例子如下:
70+
71+
````js
72+
const __ordered = inventors.sort((a, b) => (a > b) ? 1 : -1);
73+
console.table(__ordered);
74+
````
75+
76+
### filter 和 map 的结合使用
77+
78+
这两个结合起来可以做一些有意思的事情,由于示范代码中用的页面是 Wikipedia,我重新找了个国内的页面,演示如下:
79+
80+
筛选出这一个页面中包含 CSS 的书名。代码如下:
81+
````js
82+
// https://book.douban.com/tag/web
83+
const cate = document.querySelectorAll('.subject-list h2 a');
84+
const book = links
85+
.map(link => link.title)
86+
.filter(title => title.includes('CSS'));
87+
````
88+
89+
![豆瓣书单](https://cl.ly/3X2b3i3J4719/Image%202016-12-23%20at%2010.57.01%20AM.png)
90+
91+
除此之外,你还可以去自己个人订单的页面看一下今年买过的书,需要做的就是研究一下标签的 class 值或者是其他能够筛出来的标识信息,然后构造你自己的筛选语句。
92+
93+
需要提一点,由 `querySelectorAll()` 获取到的是一个 NodeList ,它并非是 Array 类型的数据,所以并不具有 `map``filter` 这样的方法,所以如果要进行筛选操作则需要把它转化成 Array 类型,使用下面示例之中的 `Array.from()` 来转化。
94+
95+
```js
96+
var links = Array.from(document.querySelectorAll('#ordersContainer div.order div.a-row > a.a-link-normal'))
97+
98+
var object = order.map( order => {
99+
var a = {};
100+
var time = order.querySelector('.order-info span.value').textContent.trim();
101+
var title = order.querySelector('div.a-row > a.a-link-normal').textContent.trim();
102+
a["time"] = time;
103+
return a;
104+
})
105+
```
106+
107+
![Amazon 订单筛选](https://cl.ly/0m0Z3f3D3d3z/Image%202016-12-23%20at%2012.00.46%20PM.png)
108+
109+
### [reduce](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce)
110+
111+
这是一个归并数组的方法,它接受一个函数作为参数(这个函数可以理解成累加器),它会遍历数组的所有项,然后构建一个最终的返回值,这个值就是这个累加器的第一个参数。例子如下:
112+
113+
````js
114+
[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
115+
return previousValue + currentValue;
116+
});
117+
````
118+
119+
而此处我们需要统计一个给定数组中各个项的值,恰好可以用到这个方法,在累加器之中,将统计信息存入一个新的对象,最后返回统计值。
120+
121+
````js
122+
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
123+
const reduce = data.reduce( (obj, item) => {
124+
if( !obj[item] ) {
125+
obj[item] = 0;
126+
}
127+
obj[item]++;
128+
return obj;
129+
}, {});
130+
console.log(reduce);
131+
````
132+
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Array Cardio 💪</title>
6+
</head>
7+
<body>
8+
<p><em>Psst: have a look at the JavaScript Console</em> 💁</p>
9+
<script>
10+
// Get your shorts on - this is an array workout!
11+
// ## Array Cardio Day 1
12+
13+
// Some data we can work with
14+
15+
const inventors = [
16+
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
17+
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
18+
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
19+
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
20+
{ first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
21+
{ first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
22+
{ first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
23+
{ first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
24+
{ first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
25+
{ first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
26+
{ first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
27+
{ first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
28+
];
29+
30+
const people = ['Beck, Glenn', 'Becker, Carl', 'Beckett, Samuel', 'Beddoes, Mick', 'Beecher, Henry', 'Beethoven, Ludwig', 'Begin, Menachem', 'Belloc, Hilaire', 'Bellow, Saul', 'Benchley, Robert', 'Benenson, Peter', 'Ben-Gurion, David', 'Benjamin, Walter', 'Benn, Tony', 'Bennington, Chester', 'Benson, Leana', 'Bent, Silas', 'Bentsen, Lloyd', 'Berger, Ric', 'Bergman, Ingmar', 'Berio, Luciano', 'Berle, Milton', 'Berlin, Irving', 'Berne, Eric', 'Bernhard, Sandra', 'Berra, Yogi', 'Berry, Halle', 'Berry, Wendell', 'Bethea, Erin', 'Bevan, Aneurin', 'Bevel, Ken', 'Biden, Joseph', 'Bierce, Ambrose', 'Biko, Steve', 'Billings, Josh', 'Biondo, Frank', 'Birrell, Augustine', 'Black Elk', 'Blair, Robert', 'Blair, Tony', 'Blake, William'];
31+
32+
// Array.prototype.filter()
33+
// 1. Filter the list of inventors for those who were born in the 1500's
34+
const fifteen = inventors.filter(inventor => (inventor.year >= 1500 && inventor.year < 1600));
35+
36+
console.table(fifteen);
37+
38+
// Array.prototype.map()
39+
// 2. Give us an array of the inventor first and last names
40+
const fullNames = inventors.map(inventor => `${inventor.first} ${inventor.last}`);
41+
console.log(fullNames);
42+
43+
// Array.prototype.sort()
44+
// 3. Sort the inventors by birthdate, oldest to youngest
45+
// const ordered = inventors.sort(function(a, b) {
46+
// if(a.year > b.year) {
47+
// return 1;
48+
// } else {
49+
// return -1;
50+
// }
51+
// });
52+
53+
const ordered = inventors.sort((a, b) => a.year > b.year ? 1 : -1);
54+
console.table(ordered);
55+
56+
// Array.prototype.reduce()
57+
// 4. How many years did all the inventors live?
58+
const totalYears = inventors.reduce((total, inventor) => {
59+
return total + (inventor.passed - inventor.year);
60+
}, 0);
61+
62+
console.log(totalYears);
63+
64+
// 5. Sort the inventors by years lived
65+
const oldest = inventors.sort(function(a, b) {
66+
const lastInventor = a.passed - a.year;
67+
const nextInventor = b.passed - b.year;
68+
return lastInventor > nextInventor ? -1 : 1;
69+
});
70+
console.table(oldest);
71+
72+
// 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name
73+
// https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris
74+
75+
// const category = document.querySelector('.mw-category');
76+
// const links = Array.from(category.querySelectorAll('a'));
77+
// const de = links
78+
// .map(link => link.textContent)
79+
// .filter(streetName => streetName.includes('de'));
80+
81+
// 7. sort Exercise
82+
// Sort the people alphabetically by last name
83+
const alpha = people.sort((lastOne, nextOne) => {
84+
const [aFirst, aLast] = lastOne.split(', ');
85+
const [bFirst, bLast] = nextOne.split(', ');
86+
return aLast > bLast ? 1 : -1;
87+
});
88+
console.log(alpha);
89+
90+
// 8. Reduce Exercise
91+
// Sum up the instances of each of these
92+
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck', 'pogostick'];
93+
94+
const transportation = data.reduce(function(obj, item) {
95+
if (!obj[item]) {
96+
obj[item] = 0;
97+
}
98+
obj[item]++;
99+
return obj;
100+
}, {});
101+
102+
console.log(transportation);
103+
104+
</script>
105+
</body>
106+
</html>
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Array Cardio 💪</title>
6+
</head>
7+
<body>
8+
<p><em>请按 F12 查看 Console 面板</em> 💁</p>
9+
<script>
10+
11+
// ## Array 基础 Day 1
12+
13+
// Some data we can work with
14+
15+
const inventors = [
16+
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
17+
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
18+
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
19+
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
20+
{ first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
21+
{ first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
22+
{ first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
23+
{ first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
24+
{ first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
25+
{ first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
26+
{ first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
27+
{ first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
28+
];
29+
30+
const flavours = ['Chocolate Chip', 'Kulfi', 'Caramel Praline', 'Chocolate', 'Burnt Caramel', 'Pistachio', 'Rose', 'Sweet Coconut', 'Lemon Cookie', 'Toffeeness', 'Toasted Almond', 'Black Raspberry Crunch', 'Chocolate Brownies', 'Pistachio Almond', 'Strawberry', 'Lavender Honey', 'Lychee', 'Peach', 'Black Walnut', 'Birthday Cake', 'Mexican Chocolate', 'Mocha Almond Fudge', 'Raspberry'];
31+
32+
const people = ['Beck, Glenn', 'Becker, Carl', 'Beckett, Samuel', 'Beddoes, Mick', 'Beecher, Henry', 'Beethoven, Ludwig', 'Begin, Menachem', 'Belloc, Hilaire', 'Bellow, Saul', 'Benchley, Robert', 'Benenson, Peter', 'Ben-Gurion, David', 'Benjamin, Walter', 'Benn, Tony', 'Bennington, Chester', 'Benson, Leana', 'Bent, Silas', 'Bentsen, Lloyd', 'Berger, Ric', 'Bergman, Ingmar', 'Berio, Luciano', 'Berle, Milton', 'Berlin, Irving', 'Berne, Eric', 'Bernhard, Sandra', 'Berra, Yogi', 'Berry, Halle', 'Berry, Wendell', 'Bethea, Erin', 'Bevan, Aneurin', 'Bevel, Ken', 'Biden, Joseph', 'Bierce, Ambrose', 'Biko, Steve', 'Billings, Josh', 'Biondo, Frank', 'Birrell, Augustine', 'Black Elk', 'Blair, Robert', 'Blair, Tony', 'Blake, William'];
33+
34+
// Array.prototype.filter()
35+
// 1. Filter the list of inventors for those who were born in the 1500's
36+
// 筛选 16 世纪出生的人
37+
const fifteen = inventors.filter(function(inventor) {
38+
if (inventor.year >= 1500 && inventor.year < 1600 ) {
39+
return true;
40+
}
41+
});
42+
console.table(fifteen);
43+
44+
const __fifteen = inventors.filter(inventor =>(inventor.year >= 1500 && inventor.year < 1600));
45+
console.table(__fifteen);
46+
47+
48+
// Array.prototype.map()
49+
// 2. Give us an array of the inventors' first and last names
50+
// 展示上面发明家的姓名
51+
const fullNames = inventors.map(inventor => inventor.first + ' ' + inventor.last);
52+
// const fullNames = inventors.map(inventor => `${inventor.first} ${inventor.last}`);
53+
console.log(fullNames);
54+
55+
56+
// Array.prototype.sort()
57+
// 3. Sort the inventors by birthdate, oldest to youngest
58+
// 把这些人从大到小进行排序
59+
const ordered = inventors.sort(function(firstName, secondName) {
60+
if(firstName.year > secondName.year) {
61+
return 1; // 对 sort 函数,返回值为 -1 排在前面,1 排在后面
62+
} else {
63+
return -1;
64+
}
65+
});
66+
console.table(ordered);
67+
68+
const __ordered = inventors.sort((a, b) => (a > b) ? 1 : -1);
69+
console.table(__ordered);
70+
71+
72+
// Array.prototype.reduce()
73+
// 4. How many years did all the inventors live
74+
// 他们所有人一共活了多少岁
75+
// 下面三种写法是一样的效果
76+
var total = 0;
77+
for(var i = 0; i < inventors.length; i++) {
78+
total += inventors[i].passed - inventors[i].year;
79+
}
80+
console.log(total);
81+
82+
var totalYears = inventors.reduce(function(total, inventor) {
83+
return total + inventor.passed - inventor.year;
84+
}, 0);
85+
console.log(totalYears);
86+
87+
const totalYear = inventors.reduce( (total, inventor) => {
88+
return total + inventor.passed - inventor.year;
89+
}, 0);
90+
console.log(totalYear);
91+
92+
// 5. Sort the inventors by years lived、
93+
// 按照他们在世的岁数进行排序
94+
const oldest = inventors.sort( (a, b) => {
95+
const last = a.passed - a.year;
96+
const next = b.passed - b.year;
97+
return (next < last) ? -1 : 1;
98+
});
99+
console.table(oldest);
100+
101+
// 6. create a list of Boulevards in Paris that contain 'de' anywhere in the name
102+
// https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris
103+
104+
// 这个是超级酷的一个玩法,打开上面的网页。然后输入下面的语句,就可以筛选出页面中含有 'de' 这个词的所有街道的名称
105+
106+
// const category = document.querySelector('.mw-category');
107+
// const links = Array.from(category.querySelectorAll('a'));
108+
// const de = links
109+
// .map(link => link.textContent)
110+
// .filter(streetName => streetName.includes('de'));
111+
112+
113+
// 下面是我在豆瓣里筛选书名里含有 CSS 的书的代码
114+
// https://book.douban.com/tag/web
115+
const cate = document.querySelectorAll('.subject-list h2 a');
116+
const book = links
117+
.map(link => link.title)
118+
.filter(title => title.includes('CSS'));
119+
120+
121+
// 7. sort Exercise
122+
// Sort the people alphabetically by last name
123+
// 按照姓氏的字母进行排序
124+
const sortName = inventors.sort( (a, b) => {
125+
return (a.last > b.last) ? 1 : -1;
126+
})
127+
console.table(sortName);
128+
129+
130+
// 8. Reduce Exercise
131+
// Sum up the instances of each of these
132+
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
133+
const reduce = data.reduce( (obj, item) => {
134+
if( !obj[item] ) {
135+
obj[item] = 0;
136+
}
137+
obj[item]++;
138+
return obj;
139+
}, {});
140+
console.log(reduce);
141+
142+
</script>
143+
</body>
144+
</html>

0 commit comments

Comments
 (0)