检查对象参数是否未定义

check if object parameter is undefined

本文关键字:未定义 是否 参数 对象 检查      更新时间:2023-09-26

我有一个类似于这里的情况:Javascript检查对象属性是否存在,即使对象是未定义的

我的问题是,如果你有一个属性链会发生什么。例子:

var obj = {'a': {'b': {'c': {'d': 'I exists'}}}}

我需要检查'd'是否被定义。为了不出现错误,我必须这样检查:

if (typeof obj != 'undefined' && typeof obj['a'] != 'undefined' && typeof obj['a']['b'] != 'undefined' && typeof obj['a']['b']['c'] != 'undefined' && typeof obj['a']['b']['c']['d'] != 'undefined')

你可以看到这有多烦人。以999级深层元素为例。有没有办法消除前n-1个条件?

使用try-catch解决方案:

var check = function(obj) {
  try {
    return (typeof obj.a.b.c.d !== 'undefined');
  } catch (e) {
    return false;
  }
};
alert(check({
  'a': {
    'b': {
      'c': {
        'd': 'I exists'
      }
    }
  }
}));

你可以这样尝试:

function checkUndefined(obj) {
  var x = Array.prototype.slice.call(arguments, 1);
  for (var i = 0; i < x.length; i++) {
    if (!obj || !obj.hasOwnProperty(x[i])) {
      return false;
    }
    obj = obj[x[i]];
  }
  return true;
}

就像Tushar在他的回答中所说的:

你不能摆脱第一个n - 1条件

所以你只需要缩短你的语句,这样就不会那么长了。

检查下面我创建的例子:

<<p> JSFIDDLE例子/strong>
var obj = {'a': {'b': {'c': {'d': 'I exists'}}}};
for (var key in obj)
{
    if (obj && obj.a.b.c.d) 
    { 
        console.log(obj.a.b.c.d);
    }
}

您可以按以下方法检查值是否为真。

你不能去掉第一个n - 1条件,但是你可以缩短语句

if (obj && obj.a && obj.a.b && obj.a.b.c && typeof obj.a.b.c.d !== 'undefined')
    // Use of obj.a.b.c.d is considered safe here

试着像下面这样写你自己的属性检查器:

JavaScript:

function test(object) {
    var restOfKeys = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        restOfKeys[_i - 1] = arguments[_i];
    }
    var propertyToTest;
    if (object === undefined || !restOfKeys.length) {
        return false;
    }
    propertyToTest = restOfKeys.shift();
    if (restOfKeys.length) {
        return test.apply(void 0, [object[propertyToTest]].concat(restOfKeys));
    }
    return object[propertyToTest] !== undefined;
}
var toTest = { a: { b: { c: "asd" } } };
alert(test(toTest, "a", "b", "c"));

打印稿:

function test(object: any, ...restOfKeys: string[]) {
    let propertyToTest: string;
    if (object === undefined || !restOfKeys.length) {
        return false;
    }
    propertyToTest = restOfKeys.shift();
    if (restOfKeys.length) {
        return test(object[propertyToTest], ...restOfKeys);
    }
    return object[propertyToTest] !== undefined;
}

var toTest = { a: { b: { c: "asd" } } };
alert(test(toTest, "a", "b", "c"));

源代码在此

var obj = {a:undefined,b:undefined,c:undefined,d:'I exists'};
  if(typeof obj['a'] === 'object'){alert(typeof obj['a']);}
  else if(typeof obj['b'] === 'object'){alert(typeof obj['b']);}
  else if(typeof obj['c'] === 'object'){alert(typeof obj['c']);}
  else{alert(typeof obj['d']+' : '+obj['d']);}

查看这里http://www.w3schools.com/js/js_datatypes.asp的数据类型这里是http://www.w3schools.com/js/js_arrays.asp for array