原文指路:
1.写好 JS 条件语句的 5 条守则https://mp.weixin.qq.com/s/CEIg_JxE_YC94Uu9uRtpMg
--1.多重判断时使用 Array.includes
将判断条件抽取到一个数组内,然后在if判断内部,使用 Array.includes
--2.更少的嵌套,尽早 Return
if (fruit) --------> if (!fruit) throw new Error('No fruit!');
尽早抛出错误,优化if-else结构,但是不要过度使用,否则影响代码的可读性并且增加认知负载。
--3.使用默认参数和解构
关于解构----https://dmitripavlutin.com/5-interesting-uses-javascript-destructuring/
译文:https://www.jb51.net/article/169392.htm
**swap variables 交换变量
[a, b] = [b, a];
已知a,b的值,构成数组然后赋值给左边数组。
**access array item 访问数组
const colors = [ ]
const [ firstItem = 'one' ] = colors;
const [, secondItem = 'two' ] = colors;
firstItem; //one
secondItem; // two
**Immutable operations 不可变操作
利用...省略号来实现数组的截取操作。
const num = [1,2,3];
const [,...num1] = num;
num1; // [2,3]
num; //[1,2,3]
可见该操作仅仅实现了截取数组元素的同时新建了一个新的数组,而且不影响原数组的元素个数。num1就是截取元素之后的新建的数组。
const arr = {
foo : ' foo ',
eoo : 'eoo'
};
const { foo , ...arr1 } = arr;
arr1; // { eoo : 'eoo' }
arr; //原数组
** Destructuring iterables 解构迭代的值
conststr='cheese';const[firstChar='']=str;firstChar;// => 'c'
可自定义迭代器
** Destructuring dynamic properties 解构动态属性
function greet ( obj ,nameProp) {
const { [nameProp] : name = 'newName' } = obj ;
return ` hello ${name}!`
greet({ name : 'bat' } ,'name'); //hello bat!
greet ( {},'name'); //hello newName!
可见,greet 函数有两个参数,其中一个对象,另一个是属性名。其中,当属性值不存在时,可显示默认属性值newName.
Destructuring works great if you want to access object properties and array items.
*如果你想访问对象属性和数组项,解构将十分有用!*
JavaScript提供了更多的可能性,因为你可以通过扩展迭代器实现自定义的解构逻辑。