JS 检查深层对象属性是否存在[重复]

2024-05-03

我正在尝试找到一种优雅的方法来检查对象中是否存在某些深层属性。因此,实际上试图避免对未定义的情况进行巨大的保护性检查,例如。

if ((typeof error !== 'undefined') && 
  (typeof error.responseJSON !== 'undefined') &&
  (typeof error.responseJSON.error) && 
  (typeof error.responseJSON.error.message)) {
      errorMessage = error.responseJSON.error.message;
}

我正在考虑的是一个像这样的便利功能

if (exists(error.responseJSON.error.message)) { ... }

有任何想法吗?为了方便起见,使用下划线 http://underscorejs.org/-library 可以解决这个问题。


有几种可能:

试着抓

try {
  errorMessage = error.responseJSON.error.message;
} catch(e) { /* ignore the error */}

失败的原因:

Object.defineProperty(error, 'responseJSON', {
  get: function() { throw new Error('This will not be shown')
});

&&

errorMessage = error && error.responseJSON && error.responseJSON.error && error.responseJSON.error.message;

失败的原因:

error.responseJSON = 0;
// errorMessage === 0 instead of undefined

function

function getDeepProperty(obj,propstr) {
  var prop = propstr.split('.');
  for (var i=0; i<prop.length; i++) {
    if (typeof obj === 'object')
      obj = obj[prop[i]];
  }
  return obj;
}

errorMessage = getDeepProperty(error, 'responseJSON.error.message');

// you could put it all in a string, if the object is defined in the window scope

失败的原因:

// It's hard(er) to use

功能替代- 请参阅@Olical 的评论

function getDeepProperty(obj) {
  for (var i=1; i<arguments.length; i++) {
    if (typeof obj === 'object')
      obj = obj[arguments[i]];
  }
  return obj;
}

errorMessage = getDeepProperty(error, 'responseJSON', 'error', 'message');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JS 检查深层对象属性是否存在[重复] 的相关文章

随机推荐