写给前端小白的入门技术白皮书06-?? 与 ?.

191 阅读1分钟

?? 与 ?.

空值合并操作符(??)

空值合并操作符 ?? 与逻辑或操作符 || 的区别

  • || 会把0 , ‘’,undefined, null 都转化为false
console.log('' || 'World')           // World
console.log(0  || 'World')           // World
console.log(null || 'World')         // World
console.log(undefined || 'World')    // World
  • ??只会把undefined, null 都转化为false
console.log('' ?? 'World')           // ''
console.log(0  ?? 'World')          // 0
console.log(null ?? 'World')         // World
console.log(undefined ?? 'World')    // World

可选链操作符(?.)

?. 算是链式操作符(.)的增强版,在链式操作过程中,可能会出现中间某个操作值为空(null 或 undefined)的情况,在这种情况下就会报错

let person = {
    name: "zdk",
    education: null
}

let school = person.education.school  // 此时会报错
let school2 = person.education?.school // 此时不会报错

组合使用

let person = {
    name: "zdk",
    education: null
}

let school = person.education?.school ?? "暂无大学信息"
console.log(school)  // "暂无大学信息"