js优化写法
判断对象有值赋值
let _is_obj_null = ( Object.key(obj) || [] ).length ? obj : {}
复制代码
优化if判断
let flag // 判断条件
if(flag = condition_1){
return
}
if(flag = condition_2){
return
}
// 非condition_1 非condition_2的话
return
复制代码
赋值有默认值
// 函数有默认值
function mua ({time = new Date(), origin_obj = {}, origin_fun = () => {}} = {}) {
console.log('time',time)//time Wed Apr 14 2021 23:30:36 GMT+0800 (China Standard Time)
console.log('origin_obj',origin_obj)//origin_obj {}
console.log('origin_fun',origin_fun())// undefined
}
// 变量有默认值
let _mi_a_ne = this.another_var || 0 // 0
复制代码
for await
let count = 0
let aynsc_fun = () => {
return new Promise(reslove => {
setTimeout(() => {
count++
console.log('aynsc_fun setTimeout',count)
reslove(count)
},2e3)
})
}
let do_func = async () => {
for(let i = 0; i < 5; i++) {
let result = await aynsc_fun()
console.log(result)
}
}
// aynsc_fun setTimeout 1
// 1
// aynsc_fun setTimeout 2
// 2
// aynsc_fun setTimeout 3
// 3
// aynsc_fun setTimeout 4
// 4
// aynsc_fun setTimeout 5
// 5
复制代码
for 解构赋值
let biu = [
{id:1, label:'a'},
{id:2, label:'b'},
{id:3, label:'c'},
]
for (let {id, label} of biu) {
console.log('label',label)
}
// label a
// label b
// label c
// for...in 因为循环项是Object.key().length //所以不能解构赋值
复制代码
向下取整(数值趋于0的方向)
let num = 9.99 | 0 // 9
let num2 = -9.99 | 0 // -9
let num3 = ~~15.99 // 15
let num4 = ~~-15.99 // -15
复制代码
对象是否存在某个属性
let obj = {
personal:{
name:'xiaoming',
weapon:{
main:'ex sword',
sub:'knife'
}
}
}
let _exist_1 = obj?.personal?.weapon?.sub
let _exist_2 = obj && obj.personal && obj.personal.weapon && obj.personal.weapon.sub
console.log('_exist_1',_exist_1) // knife
console.log('_exist_2',_exist_2) // knife
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END