JavaScript优化技术

前言

JavaScript优化技术


1.多个条件优化

//old
if(x==='a'||x==='b'||x==='c'){
	
}
//shorthand
if(['a','b','c'].includes(x)){

}

2. if else

//old
if(x>5){
	
}else{
}
//shorthand
(x>5)?true:false

3. 空 未定义 空检查

//old
if(x!==null||x!==undefined||x!==''){
	
}
//shorthand
let y=x||''

4. 空合并运算符??

//如果左侧为null或未定义 则返回右侧的值 
const x=null??'default'

5. 给多个变量赋值

let [x1,x2,x3]=[1,2,3]

6. 如果存在

//old
if(x===true){}
//shorthand
if(x){}

7. 多个条件的and(&&)运算符

//old
if(x){
	dosomethindg()
}
//shorthand
x&&dosomething()

8. Switch 将条件保存在键值对象中,并可以根据条件使用

//old
switch (x) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // And so on...
}
//shorthand
let x={
	1:x1,
	2:x2,
	3:x3
}
x[something]&&x[something]()

9. 隐式返回速记

//使用箭头功能,我们可以直接返回值,而不必编写return语句
something=x=>{
	somthing
}

10. 小数基指数

//old
for(let i =0;i<10000;i++){}
//shorthand
for(let i=0;i<1e4;i++){}

11. 对象属性分配

//old
let x={x1:x1,x2:x2}
//shorthand
let x={x1,x2}

12. Object.entries() 将对象转换为对象数组

const data={test1:'abc',test2:'abc',test3:'abc'}
const arr=Object.entries(data)
console.log(arr)
//
/*
[
['test1':'abc'],
['test2':'abc'],
['test3':'abc'],
]
*/

13. Object.values()

const data={test1:'abc',test2:'abc',test3:'abc'}
const arr=Object.values(data)
console.log(arr)
//
/*
[
'abc','abc','abc'
]
*/

14. Double Bitwise

//old
Math.floor(1.9)===1//true
//shorthand 双重NOT按位运算符方法仅适用于32位整数
~~1.9===1//true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值