javascript - javascript 中是否有空合并 (Elvis) 运算符或安全导航运算符?

标签 javascript jquery groovy safe-navigation-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

最佳答案

您可以使用逻辑“或”运算符代替 Elvis 运算符:

例如 displayname = user.name || "Anonymous" .

但 Javascript 目前没有其他功能。我建议查看 CoffeeScript如果您想要替代语法。它有一些与您正在寻找的类似的速记。

例如存在运算符

zip = lottery.drawWinner?().address?.zipcode

功能快捷键

()->  // equivalent to function(){}

性感的函数调用

func 'arg1','arg2' // equivalent to func('arg1','arg2')

还有多行注释和类。显然,您必须将其编译为 javascript 或以 <script type='text/coffeescript>' 的形式插入到页面中。但它增加了很多功能:)。使用 <script type='text/coffeescript'>实际上仅用于开发而非生产。

关于javascript - javascript 中是否有空合并 (Elvis) 运算符或安全导航运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6613952/

相关文章:

javascript - 访问子属性值

javascript - 如何通过 REST API 提交 Jenkins 作业?

javascript - 仅带有日期选择器的自定义 jQuery UI 下载不包含所有 css

javascript - CSS nth-child 选择器不适用于 JS 创建的表

javascript - 异步函数头脑 Storm - Babel

java - 减去毫秒不会给出预期的结果

jenkins - 从Jenkinsfile写日志

javascript - 如何从方法访问构造函数中声明的变量?

jquery - 如何设置div高度以自动调整背景大小?

javascript - jQuery slider 建议