Javascripts 中的 if … else 用起来倒是很方便,但是看起来就不舒服了
1if (true) {
2}
3
4if (true) {
5}
6
7if (true) {
8 if (true) {
9 if (true) {
10 }
11 } else {
12 }
13} else {
14}
上面看起来很闹心吧,下面讲讲优化:
一、三元优化
if (ture) else可以用三元操作符来优化它:
1// Bad 😥
2if (true) {
3 console.log("Congratutions!")
4} else {
5 console.warn("Oops, something went wrong!")
6}
7
8// Great 🥰
9true
10 ? console.log("Congratutions")
11 : console.warn("Oops, something went wrong!")
二、与优化
true的情况下才执行可以用与来进行优化:
1if (true) {
2 alert(1)
3}
4
5// is equals to:
6
7true && alert(1)
三、提前返回
如果有多个判断,按照复杂程度,从上到下,提前返回。
1function handleRequest(req) {
2 if (req.code >= 500) {
3 return "Server error";
4 }
5 if (req.code >= 404) {
6 return "Cilent error";
7 }
8 return "Suceess";
9}
四、类表格优化
下面是类似表格似的选择,通常会用 switch 来进行优化
1// Bad 😥
2const weekday = (num) => {
3 if (num === 1) {
4 return "Monday"
5 } else if (num === 2) {
6 return "Tuesday"
7 } else if (num === 3) {
8 return "Wednesday"
9 } else if (num === 4) {
10 return "Thursday"
11 } else if (num === 5) {
12 return "Friday"
13 } else if (num === 6) {
14 return "Saturday"
15 } else if (num === 7) {
16 return "Sunday"
17 } else {
18 return "Unknown"
19 }
20}
21
22console.log(weekday(1)) // Monday
switch 也不是最优解,用对象的键值对来解:
1const weekday = (option) => {
2 let obj = {
3 1: "Monday",
4 2: "Tuesday",
5 3: "Wednesday",
6 4: "Thursday",
7 5: "Friday",
8 6: "Saturday",
9 0: "Sunday"
10 }
11 return obj[option] ?? "Unknown"
12}
13
14console.log(weekday(1)) // Monday
也可以用 ES6 的 map 来实现:
1// Great 🥰
2const weekday = (num) => {
3 const map = new Map()
4 .set(1, "Monday")
5 .set(2, "Tuesday")
6 .set(3, "Wednesday")
7 .set(4, "Thursday")
8 .set(5, "Friday")
9 .set(6, "Saturday")
10 .set(7, "Sunday");
11 return map.has(num) ? map.get(num) : "Unknown";
12};
13
14console.log(weekday(1));
五、选项多对一的数组优化
看如下代码,多个选项对应一个返回:
1const getContinent = (option) => {
2 if (option === "China" || option === "Japan") {
3 return "Asia";
4 }
5 if (option === "Germany" || option === "France") {
6 return "Europe";
7 }
8};
9
10console.log(getContinent("China"));
使用数组来容纳多个选项,然后用 includes 来判断并返回
1const getContinent = (option) => {
2 const Asia = ["China", "Japan"];
3 const Europe = ["Germany", "Franch"];
4 if (Asia.includes(option)) return "Asia";
5 if (Europe.includes(option)) return "Europe";
6 return "Unknown";
7};
8
9console.log(getContinent("China")); // Asia
进一步优化,用 && 与优化
1const getContinent = (option) => {
2 let [result, setResult] = ["unknown", (str) => (result = str)];
3 const Asia = ["China", "Japan"];
4 const Europe = ["Germany", "Franch"];
5 Asia.includes(option) && setResult("Asia");
6 Europe.includes(option) && setResult("Europe");
7 return result;
8};
9
10console.log(getContinent("China"));