In Javascript. how can I tell if a field exists inside an object?

前端 未结 5 842
余生分开走
余生分开走 2021-01-31 07:12

And of course I want to do this code-wise. It\'s not that there isn\'t alternative to this problem I\'m facing, just curious.

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 07:32

    UPDATE: use the hasOwnProperty method as Gary Chambers suggests. The solution below will work, but it's considered best practice to use hasOwnProperty.

    if ('field' in obj) {
    }
    

提交回复
热议问题