我正在查看代码库,不幸的是看到了很多代码,例如:
if (module && module.foo && module.foo.bar && module.foo.bar.baz)
我开始在谷歌上搜索,看看是否有一个库或其他东西可以让这种情况变得可以忍受;没有找到,但我仍然确定某处存在)。我写得很快,但有点讨厌它,因为传入根对象和一个字符串在'。'上分割很丑;希望有更好的东西:
<!DOCTYPE html>
<html>
<head>
<title>safe tests</title>
<script type="text/javascript">
function assert(condition, desc) {
var d = document, li = d.createElement("li");
li.className = condition ? "pass" : "fail";
li.appendChild(d.createTextNode(desc));
d.getElementById('results').appendChild(li);
}
</script>
<style type="text/css">
#results li.pass { color: green; }
#results li.fail{ color: red; }
</style>
</head>
<body>
<ul id="results"></ul>
<script type="text/javascript">
function safe(root, s) {
var split = s.split('.'), checked = root;
for (var i = 0, len = split.length; i < len; i++) {
if (checked[split[i]]) {
checked = checked[split[i]];
continue;
} else {
return false;
}
}
return true;
}
var foo = {
bar: {
baz: {
qux: 'yippie!'
}
}
}
assert(safe(foo, 'bar'), "finds first sub object");
assert(safe(foo, 'bar.baz'), "finds first and then second sub object");
assert(safe(foo, 'bar.baz.qux'), "finds first, second, third, sub object");
assert(!safe(foo, 'bar.baz.qux.NOT'), "rejects if not defined (end)");
assert(!safe(foo, 'NOPE.baz.qux.NOT'), "rejects if not defined (front)");
assert(!safe(foo, 'bar.NO.baz'), "rejects if not defined (middle)");
</script>
</body>
</html>
任何已经处理这个问题的建议或库是精简的?