Javascript equivalent of Rails try method

后端 未结 6 794
醉话见心
醉话见心 2021-02-05 01:56

In Rails I can do this:

 x = user.try(:name)

this method returns nil if user is nil else user.name

6条回答
  •  孤城傲影
    2021-02-05 02:21

    Isn't that the same as what this gives you in Javascript:

    user['name']
    user.name
    

    This returns undefined instead of nil but that's equivalent in most cases. I think the reason Rails needs the try method is because you cannot access instance variables unless they are made accessible.

    To add to @PSL's approach, I usually do something like:

    var x = user || {},
        y = x.name || {},
        z = y.first_name;
    

提交回复
热议问题