javascript 中是否有空合并(Elvis)运算符或安全导航运算符? [英] Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
问题描述
我会举例说明:
猫王接线员 (?:)
<块引用>猫王运算符"是一个缩写Java的三元运算符.一这很方便的实例是为了返回一个合理的默认"值如果表达式解析为 false 或空值.一个简单的例子可能看起来像这个:
def 性别 = user.male ?"male" : "female"//传统的三元运算符用法def displayName = user.name ?: "Anonymous"//更简洁的Elvis操作符
<块引用>
安全导航操作员 (?.)
使用了安全导航操作符以避免 NullPointerException.通常,当您参考您可能需要验证的对象在访问之前它不为空对象的方法或属性.为了避免这种情况,安全导航运算符将简单地返回 null而不是抛出异常,比如所以:
def user = User.find( "admin" )//如果'admin'不存在,这可能为空def streetName = user?.address?.street//如果 user 或 user.address 为 null,streetName 将为 null - 不抛出 NPE
您可以使用逻辑OR"运算符代替 Elvis 运算符:
例如 displayname = user.name ||匿名"
.
但 Javascript 目前没有其他功能.如果您需要其他语法,我建议您查看 CoffeeScript.它有一些与您要查找的内容类似的速记.
例如存在运算符
zip = lottery.drawWinner?().address?.zipcode
功能快捷键
()->//等价于 function(){}
性感的函数调用
func 'arg1','arg2'//等价于 func('arg1','arg2')
还有多行注释和类.显然,您必须将其编译为 javascript 或作为 <script type='text/coffeescript>'
插入页面,但它添加了很多功能 :) .使用 实际上仅用于开发而非生产.
I'll explain by example:
Elvis Operator (?: )
The "Elvis operator" is a shortening of Java's ternary operator. One instance of where this is handy is for returning a 'sensible default' value if an expression resolves to false or null. A simple example might look like this:
def gender = user.male ? "male" : "female" //traditional ternary operator usage
def displayName = user.name ?: "Anonymous" //more compact Elvis operator
Safe Navigation Operator (?.)
The Safe Navigation operator is used to avoid a NullPointerException. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. To avoid this, the safe navigation operator will simply return null instead of throwing an exception, like so:
def user = User.find( "admin" ) //this might be null if 'admin' does not exist
def streetName = user?.address?.street //streetName will be null if user or user.address is null - no NPE thrown
You can use the logical 'OR' operator in place of the Elvis operator:
For example displayname = user.name || "Anonymous"
.
But Javascript currently doesn't have the other functionality. I'd recommend looking at CoffeeScript if you want an alternative syntax. It has some shorthand that is similar to what you are looking for.
For example The Existential Operator
zip = lottery.drawWinner?().address?.zipcode
Function shortcuts
()-> // equivalent to function(){}
Sexy function calling
func 'arg1','arg2' // equivalent to func('arg1','arg2')
There is also multiline comments and classes. Obviously you have to compile this to javascript or insert into the page as <script type='text/coffeescript>'
but it adds a lot of functionality :) . Using <script type='text/coffeescript'>
is really only intended for development and not production.
这篇关于javascript 中是否有空合并(Elvis)运算符或安全导航运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!