相同点
用法相同,都是前后是值,中间用符号连接。根据前面的值来判断最终返回前面的值还是后面的值。
值1 ?? 值2
值1 || 值2
不同点
判断方式不同:
-
当使用 ?? 时,只有当 值1 为 null 或 undefined 时才返回 值2 ;
-
使用 || 时, 值1 会转换为 布尔值 判断,为 true 返回 值1 , false 返回 值2
// ?? undefined ?? 2 // 2 null ?? 2 // 2 0 ?? 2 // 0 "" ?? 2 // "" true ?? 2 // true false ?? 2 // false // || undefined || 2 // 2 null || 2 // 2 0 || 2 // 2 "" || 2 // 2 true || 2 // true false || 2 // 2