gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:15:53 24 4
gpt4 key购买 nike

我会举例说明:

猫王运算符 (?: )

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com