Ada*_*dam 4 javascript arrays children if-statement object
我想只在对象的子数组中包含元素时显示一些内容.但有时对象本身没有定义,所以如果object或object.child不在范围内,这样做会失败:
if(object.child.length){
alert('hello world');
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
Uncaught ReferenceError: object is not defined
Run Code Online (Sandbox Code Playgroud)
所以我必须添加两个额外的if条件来检查是否定义了对象及其子节点:
if(typeof object !== 'undefined'){
if(typeof object.child !== 'undefined'){
if(object.child.length){
alert('hello world');
}
}
}
Run Code Online (Sandbox Code Playgroud)
围绕这个编写函数也存在问题:
function isset(value){ ... }
if(isset(object.child.length)({ ... } // <-- still raises error that object is not defined
Run Code Online (Sandbox Code Playgroud)
有更清洁,更短的方法吗?
T.J*_*der 10
你可以放一个警卫:
if(object && object.child && object.child.length){
Run Code Online (Sandbox Code Playgroud)
以上辩护object和object.child存在undefined或null(或任何其他虚假价值); 它的工作原理是因为所有非null对象引用都是真实的,所以你可以避免使用冗长的typeof object !== "undefined"形式.你可能不需要上面的两个守卫,如果你确定object.child如果object确实存在的话.但两者都是无害的.
值得注意的是,即使在检索值时这也很有用,而不仅仅是测试它们.例如,假设您有(或可能没有!)object.foo,其中包含您要使用的值.
var f = object && object.foo;
Run Code Online (Sandbox Code Playgroud)
如果object是假的(undefined或者null是典型案例),那么f将收到该假值(undefined或null).如果object是真实的,f将收到的价值object.foo.
||是好奇强大的以类似的方式.