diveDylan / blog

My blog, detail is in the issues list
2 stars 0 forks source link

一些写法的优化 #20

Open diveDylan opened 4 years ago

diveDylan commented 4 years ago

三元和与的取舍

以下是同时代码片段出现较多的情况

<!--bad -->
const params = {
    orderId: order ? order.id : undefined
    prodcutId: order ? (order.product ? order.product.id : undefined) :  undefined : undefined
}

这里另一个选项是undefined,所以改写:

const params = {
    orderId: order && order.id,
   prodcutId: order && order.product && order.product.id
}
// notice  if obj = null
const obj = null
const a = obj && obj.id // null

// aslo number or boolean
const a = 0
a && a.a //0
const c = false
c && c.a = false