Detecting an undefined object property

后端 未结 30 2865
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 05:42

    function isUnset(inp) {
      return (typeof inp === 'undefined')
    }
    

    Returns false if variable is set, and true if is undefined.

    Then use:

    if (isUnset(var)) {
      // initialize variable here
    }
    

提交回复
热议问题