Javascript equivalent of Rails try method

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

    I don't think so. Why not roll your own? Not exactly equivalent but does the job.

    function tryMe(obj) {
      return obj === null || obj === undefined ? null : obj;
    }
    

提交回复
热议问题