Javascript equivalent of Rails try method

后端 未结 6 805
醉话见心
醉话见心 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:31

    You can use logical AND (&&) operator. It works differently than in most of the languages because its result is not a boolean. For example:

    const x = user && user.name;
    

    The table below shows all possible outcomes of using this operator:

    +--------------+-----------------------+
    |    user      | x = user && user.name |
    +--------------+-----------------------+
    | undefined    | undefined             |
    | null         | null                  |
    | {}           | undefined             |
    | {name:''}    | ''                    |
    | {name:'Jon'} | 'Jon'                 |
    +--------------+-----------------------+
    

提交回复
热议问题