实用JS技巧
1.多个if条件
if(x=='a'||x=='b'||x=='c'){}
better:
if(['a','b','...'].includes(x)){}
2.假值(undefined、null、0、false、NaN、空字符串)检查
if (test1 !== null || test1 !== undefined || test1 !== "") {
let test2 = test1;
}
better:
let test2 = test1 || ""
if(test1 === true) or if(test1 !=="") or if(test1!== null)
better:
if(test1){...}else{...}
3.空值合并符 ??
**** 只有当左边是 null,undefined 的时候 才会返回右边的值;
const a = 0 ?? 42
**** 与 || 不同,||会在左侧操作数为假值时返回右侧操作数
**** null检查和默认赋值:
let test2 = null ?? "" //undefined
(有待考究)
**** undefined:
const test = undefined ?? "default"
expecred output: "default"
**** 比较后返回
function checkReturn(){
if(test !== undefined){ return test;} else { return fun("test")}
}
better:
function checkReturn(){
return test ?? fun("test")
}
4.使用可选链操作符号 ?.
?. 链判断运算符,允许开大人员深度嵌套在对象链总的属性值,而不必验证每个引用。当引用为空的时候,表达式停止计算并返回undefined
const travelPlans = {
destination: "DC",
monday: {
location: "National Mall",
budget: 200,
},
};
bad:
const res =
travelPlans &&
travelPlans.tuesday &&
travelPlans.tuesday.location &&
travelPlans.tuesday.location.href;
better:
const res1 = travelPlans?.tuesday?.location?.href
//undefined
5.用于多个条件判断的 && 操作符
如果只在变量为true时才调用函数,可以使用&& 操作符
test ==1 && fun()
当在react 中想要有条件的渲染组件的时候,(&&) 短路写法:
<div>{ this.state.isLoading && <Loading/>(组件名)}</div>
5.switch 简化
**** 将条件保存在键值对象中
bad:
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
better:
var data = {
1:test1,
2:test2,
3:test3,
}
// 如果type 在 data中存在, 则执行对应的函数
data[type] && data[type]();
5.默认参数值
//函数默认值
better:
add = (test = 1,test = 2) => test1 +test2
add()
6.条件查找简化
// bad
if (type === "test1") {
test1();
} else if (type === "test2") {
test2();
} else if (type === "test3") {
test3();
} else if (type === "test4") {
test4();
} else {
throw new Error("Invalid value " + type);
}
better:
var types =[test0,test1,test2,test4,test5]
types[type] && type[type]()
7.解构赋值
const { test1, test2, test3 } = this.data;