Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:检查对象子数组长度,即使未定义对象_Javascript_Arrays_Object_If Statement_Children - Fatal编程技术网

Javascript:检查对象子数组长度,即使未定义对象

Javascript:检查对象子数组长度,即使未定义对象,javascript,arrays,object,if-statement,children,Javascript,Arrays,Object,If Statement,Children,我只想在对象的子数组中包含元素时显示一些内容。但有时对象本身没有定义,因此如果对象或对象。子对象不在作用域中,则此操作失败: if(object.child.length){ alert('hello world'); } 其结果是: Uncaught ReferenceError: object is not defined 因此,我必须添加两个附加的if条件来检查对象及其子对象是否已定义: if(typeof object !== 'undefined'){ if(typ

我只想在对象的子数组中包含元素时显示一些内容。但有时对象本身没有定义,因此如果
对象
对象。子对象
不在作用域中,则此操作失败:

if(object.child.length){
    alert('hello world');
}
其结果是:

Uncaught ReferenceError: object is not defined
因此,我必须添加两个附加的if条件来检查对象及其子对象是否已定义:

if(typeof object !== 'undefined'){
    if(typeof object.child !== 'undefined'){
        if(object.child.length){
            alert('hello world');
        }
    }
}
围绕这一点编写函数也是有问题的:

function isset(value){ ... }
if(isset(object.child.length)({ ... } // <-- still raises error that object is not defined
函数设置(值){…}

如果(isset(object.child.length)({…}/您可以设置一个防护:

if(object && object.child && object.child.length){
上述方法可防止
对象
对象。子对象
未定义的
空值
(或任何其他虚假值);它之所以有效,是因为所有非
空值
对象引用都是真实的,因此您可以避免对象的详细类型!=“未定义”
form。如果您确信
object.child
将存在,则您可能不需要上述两种防护。但是,如果
object
存在,则具有这两种防护是无害的

值得注意的是,即使在检索值时,这也很有用,而不仅仅是在测试值时。例如,假设您有(或可能没有!)
object.foo
,其中包含您要使用的值

var f = object && object.foo;
如果
object
为假(
undefined
null
是典型的情况),则
f
将接收假值(
undefined
null
)。如果
object
为真值,
f
将接收
object.foo
的值

|
的方式类似