Questions tagged «safe-navigation-operator»

21
javascript中是否存在null-coalescing(Elvis)运算符或安全导航运算符?
我将举例说明: 猫王算子(?:) “ Elvis运算符”是Java三元运算符的缩写。一个方便的例子是,如果表达式解析为false或null,则返回“明智的默认值”。一个简单的示例可能如下所示: def gender = user.male ? "male" : "female" //traditional ternary operator usage def displayName = user.name ?: "Anonymous" //more compact Elvis operator 安全导航操作员(?。) 安全导航运算符用于避免NullPointerException。通常,当您引用对象时,可能需要在访问对象的方法或属性之前验证其是否为null。为了避免这种情况,安全的导航运算符将只返回null而不是引发异常,例如: def user = User.find( "admin" ) //this might be null if 'admin' does not exist def streetName = user?.address?.street //streetName will be …
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.