Javascript相当于Rails的try方法 [英] Javascript equivalent of Rails try method

查看:66
本文介绍了Javascript相当于Rails的try方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails中,我可以这样做:

In Rails I can do this:

 x = user.try(:name)

此方法返回 nil if user nil else user.name 。这里 name 是在用户对象上定义的方法。

this method returns nil if user is nil else user.name. Here name is a method defined on the user object.

我知道可以在Javascript中使用 if..then..else 来完成,但是有一个等效的 compact 方法可以在Javascript?

I know it can be done using if..then..else in Javascript but is there an equivalent compact method to do the same in Javascript?

谷歌搜索指向Javascript的尝试命令,这不是我想要的。

Googling points to Javascript's try command which is not what I am looking for.

推荐答案

你可以这样做,因为没有内置的方法:

You can do this way, as there is no built in way of doing that:

var x = (user || {}).name;




  • 如果用户未定义/ null,您将获得未定义

  • 如果定义了用户,您将获得name属性(可以设置或未定义)。

  • 如果未定义用户(null),这不会破坏脚本。

    This won't break the script if user is not defined (null).

    但是必须在范围内的某个位置声明用户变量,即使其值未定义。否则你会得到错误的说明用户未定义。

    同样,如果在全局范围内,那么你可以明确地检查这个变量是否为全局属性范围,以避免上述错误

    Similarly if is in global scope then you can explicitly check for this variable as a property of global scope, to avoid the error as mentioned above

    ex:

     var x = (window.user || {}).name; // or var x = (global.user || {}).name;
    

    为了安全执行功能,

     var noop = function(){}; //Just a no operation function
    
     (windowOrSomeObj.exec || noop)(); //Even if there is no property with the name `exec` exists in the object, it will still not fail and you can avoid a check. However this is just a truthy check so you may want to use it only if you are sure the property if exists on the object will be a function.
    

    这篇关于Javascript相当于Rails的try方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆