0

Possible Duplicate:
php isset() equivalent in javascript

PHP example: http://codepad.viper-7.com/vo4wGI

<?php
var_dump( isset($something['deep']->property) ); // false
# because well, there is no such thing defined at all

JS kind of equivalent: http://jsfiddle.net/psycketom/Lp83m/ but doesn't work, because browsers appear to lookup the value first before trying to resolve it's type, and, if it's not found, you get

console.log( typeof something['deep'].property ); // Uncaught ReferenceError: something is not defined 

Is there a native function in JavaScript to properly resolve deep undefined properties?

4

2 回答 2

2

var如果您必须检查变量, 这应该可以工作..

  if (typeof(var) != 'undefined' && var != null ) {
       //do something
    }
于 2012-11-25T17:13:42.513 回答
2

您可以编写一个检查对象本身和属性的函数:

function isset(obj, prop) {
  return typeof obj !== 'undefined' ? obj.hasOwnProperty(prop) : false;
}

你会这样称呼它:

myObj = {
  "myprop1": "myvalue1"
};

isset(myObj, "myprop1"); // returns true
isset(myObj, "anotherprop"); // returns false
isset(); // returns false

编辑:要回答您的问题,没有本机函数可以这样做,如果您希望深入检查对象(如果该属性存在于对象内部的某个位置),您必须自己编写它。你可以递归地做。但我认为这样做没有任何意义,因为您不知道该属性存在于哪个“级别”(您可以返回它,但是您没有带有布尔返回值的 isset 函数)

于 2012-11-25T16:42:29.660 回答