gpt4 book ai didi

Javascript:即使 undefined object 也检查对象子数组长度

转载 作者:搜寻专家 更新时间:2023-11-01 05:01:14 27 4
gpt4 key购买 nike

我只想在对象的子数组中包含元素时显示一些内容。但有时对象本身没有定义,所以如果 objectobject.child 不在范围内,这样做会失败:

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

有没有更简洁、更短的方法来做到这一点?

最佳答案

你可以加个 guard :

if(object && object.child && object.child.length){

上面的代码防止 objectobject.childundefinednull (或任何其他虚假值);它之所以有效,是因为所有非 null 对象引用都是真实的,因此您可以避免冗长的 typeof object !== "undefined" 形式。如果您确定如果 object 存在,则 object.child 将存在,您可能不需要上面的两个守卫。但同时拥有两者是无害的。

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

var f = object && object.foo;

如果 object 是假的(undefinednull 是典型的情况),那么 f 将收到错误值(undefinednull)。如果 object 为真,f 将接收 object.foo 的值。

||curiously powerful以类似的方式。

关于Javascript:即使 undefined object 也检查对象子数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18917379/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com