原文指路:
1.寫好 JS 條件語句的 5 條守則https://mp.weixin.qq.com/s/CEIg_JxE_YC94Uu9uRtpMg
--1.多重判斷時(shí)使用 Array.includes
將判斷條件抽取到一個(gè)數(shù)組內(nèi)傀顾,然后在if判斷內(nèi)部瓷马,使用?Array.includes
--2.更少的嵌套链烈,盡早 Return
??if?(fruit) -------->??if?(!fruit)?throw?new?Error('No?fruit!');
盡早拋出錯(cuò)誤,優(yōu)化if-else結(jié)構(gòu)兼犯,但是不要過度使用,否則影響代碼的可讀性并且增加認(rèn)知負(fù)載。
--3.使用默認(rèn)參數(shù)和解構(gòu)
? ? ? ? ? ? 關(guān)于解構(gòu)----https://dmitripavlutin.com/5-interesting-uses-javascript-destructuring/
譯文:https://www.jb51.net/article/169392.htm
**swap variables 交換變量
[a, b] = [b, a];
已知a切黔,b的值砸脊,構(gòu)成數(shù)組然后賦值給左邊數(shù)組。
**access array? item 訪問數(shù)組
const colors = [ ]
const [ firstItem = 'one' ] = colors;
const [, secondItem = 'two' ] = colors;
firstItem; //one
secondItem; // two
**Immutable operations? ?不可變操作
利用...省略號來實(shí)現(xiàn)數(shù)組的截取操作纬霞。
const num = [1,2,3];
const [,...num1] = num;
num1;? ? ?// [2,3]
num;? ? //[1,2,3]
可見該操作僅僅實(shí)現(xiàn)了截取數(shù)組元素的同時(shí)新建了一個(gè)新的數(shù)組脓规,而且不影響原數(shù)組的元素個(gè)數(shù)。num1就是截取元素之后的新建的數(shù)組险领。
const arr = {
foo : ' foo ',
eoo : 'eoo'
};
const {?foo , ...arr1?} = arr;
arr1;? ? // { eoo : 'eoo' }
arr;? ? //原數(shù)組
** Destructuring iterables 解構(gòu)迭代的值
conststr='cheese';const[firstChar='']=str;firstChar;// => 'c'
可自定義迭代器
**?Destructuring dynamic properties? ? ?解構(gòu)動(dòng)態(tài)屬性
function greet ( obj ,nameProp) {
const { [nameProp] : name = 'newName' } = obj ;
return ` hello ${name}!`
greet({ name : 'bat' } ,'name');? ? //hello bat!
greet ( {},'name');? ? //hello newName!
可見,greet 函數(shù)有兩個(gè)參數(shù)绢陌,其中一個(gè)對象挨下,另一個(gè)是屬性名脐湾。其中,當(dāng)屬性值不存在時(shí)秤掌,可顯示默認(rèn)屬性值newName.
Destructuring works great if you want to access object properties and array items.
*如果你想訪問對象屬性和數(shù)組項(xiàng)愁铺,解構(gòu)將十分有用!*
JavaScript提供了更多的可能性闻鉴,因?yàn)槟憧梢酝ㄟ^擴(kuò)展迭代器實(shí)現(xiàn)自定義的解構(gòu)邏輯茵乱。