问题描述
我会用例子来解释:
Elvis Operator(?:)
def gender = user.male ? male:female//传统的三元运算符用法
def displayName = user.name?:Anonymous//更简洁的Elvis操作符
def user = User.find(admin)//如果'admin'不存在,则可能为空
def streetName = user?.address?.street // streetName将会为null,如果user或user.address为null - 没有NPE抛出
例如 displayname = user.name || 匿名
。
但是Javascript目前没有其他功能。如果您需要其他语法,建议您查看。它有一些简写,类似于你正在寻找的。 p>
例如存在的操作符
zip = lottery.drawWinner?()。address?.zipcode
功能快捷键
() - > //相当于function(){}
性感函数调用
func'arg1','arg2'//相当于func('arg1','arg2')
pre>
还有多行注释和类。很明显,你必须将它编译为javascript或者以
< script type ='text / coffeescript>'
的形式插入页面,但它增加了很多功能:)。使用< script type ='text / coffeescript'>
实际上仅用于开发而非生产。I'll explain by example:
Elvis Operator (?: )
def gender = user.male ? "male" : "female" //traditional ternary operator usage def displayName = user.name ?: "Anonymous" //more compact Elvis operator
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中是否存在null-coalescing(Elvis)运算符或安全导航运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!