考虑一下:
typeof(object.prop1.prop2) == "undefined"
,其中
object.prop1
未定义
这会输出一个javascript错误,如何处理这种情况呢? 即:没有多个if
答案 0 :(得分:0)
如果您不想重复if条件,请在try / catch块中包装,只有我能想到的方式;
try {
var x = object.prop1.prop2.prop3.prop4;
} catch(e) {
console.log("Not enough levels.");
}
编辑,
我觉得这个非常漂亮......如果你能更多地解释一下你的数据结构,也许可以提供一个明确的答案。您是否正在寻找远离建筑物的房产?前段时间我为PHP数组函数编写了一些XPath,它也可能适用于javascript对象/数组。尝试对象(它可以解决我的问题):
<html>
<head>
<body>
<script>
window.onload = function() {
function isObject(o) {
return (typeof o == 'object' && typeof o.length == 'undefined');
}
function object_xpath(object, path) {
var nodes = path.split('/');
return object_xpath_helper(object, nodes);
}
function object_xpath_helper(object, nodes) {
if (isObject(object) && nodes.length > 0) {
var node = nodes.shift();
if (nodes.length > 0 && isObject(object[node]))
return object_xpath_helper(object[node], nodes);
else if (nodes.length == 0)
return object[node];
}
return false;
}
var testObject = {
'one': {
'two': 'just a string!',
'three': {
'four': 'mhmm.',
'five': {
'findMe': 'Here I am!'
}
}
}
};
console.log(object_xpath(testObject, 'one/three/five/findMe'));
console.log(object_xpath(testObject, 'one/three/four/foobar'));
/* And you should be able to use it in conditional statements as well: */
if (object_xpath(testObject, 'one/two/nine'))
console.log("This should never be printed");
if (object_xpath(testObject, 'one/two'))
console.log("Found it!");
}
</script>
</body>
</html>
答案 1 :(得分:0)
@Björn的答案可能是最简单的方法,但有时您可能需要更多信息;在这种情况下,你只需要逐步测试;例如:
if(foo && foo.bar != undefined && foo.bar.baz != undefined ...)
答案 2 :(得分:0)
if(typeof(object.prop1) == "undefined" ? false : (typeof(object.prop1.prop2) == "undefined" ? false : true)) {
//isnt this beautifull?
}