2020年解决方案?和? ?
你现在可以直接使用?(可选链接)内联安全测试的存在。所有现代浏览器都支持它。
?? (Nullish Coalescing)可以用来设置一个默认值,如果是undefined或null。
aThing = possiblyNull ?? aThing
aThing = a?.b?.c ?? possiblyNullFallback ?? aThing
如果属性存在,?。继续进行下一个检查,或返回有效值。任何故障都将立即短路并返回未定义。
const example = {a: ["first", {b:3}, false]}
example?.a // ["first", {b:3}, false]
example?.b // undefined
example?.a?.[0] // "first"
example?.a?.[1]?.a // undefined
example?.a?.[1]?.b // 3
domElement?.parentElement?.children?.[3]?.nextElementSibling
null?.() // undefined
validFunction?.() // result
(() => {return 1})?.() // 1
为了确保默认定义的值,可以使用??。如果需要第一个真值,可以使用||。
example?.c ?? "c" // "c"
example?.c || "c" // "c"
example?.a?.[2] ?? 2 // false
example?.a?.[2] || 2 // 2
如果不检查大小写,左侧属性必须存在。如果不是,它将抛出异常。
example?.First // undefined
example?.First.Second // Uncaught TypeError: Cannot read property 'Second' of undefined
?. 浏览器支持- 92%,2021年11月
?? 浏览器支持- 92%
Mozilla的文档
--
逻辑空赋值,2020+解决方案
新的操作符目前正在添加到浏览器中,??=, ||=和&&=。它们做的并不是你想要的,但根据你代码的目的,它们可能会导致相同的结果。
注意:这些在公共浏览器版本中还不常见,但Babel应该可以很好地编译。将随着可用性更改而更新。
??=检查左边是否未定义或为空,如果已经定义则短路。如果不是,则将左边的值赋给右边的值。||=和&&=类似,但基于||和&&操作符。
基本的例子
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
对象/数组的例子
let x = ["foo"]
let y = { foo: "fizz" }
x[0] ??= "bar" // "foo"
x[1] ??= "bar" // "bar"
y.foo ??= "buzz" // "fizz"
y.bar ??= "buzz" // "buzz"
x // Array [ "foo", "bar" ]
y // Object { foo: "fizz", bar: "buzz" }
浏览器支持2021年11月- 90%
Mozilla的文档