在javascript中,是否有语法快捷方式检查嵌入对象的每一层是否存在?

编程入门 行业动态 更新时间:2024-10-21 20:32:28
本文介绍了在javascript中,是否有语法快捷方式检查嵌入对象的每一层是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

例如下面的代码

<前>if( obj.attr1.attr2.attr3.attr4 == 'constant' ) 返回;

需要改写为

<前>如果( obj.attr1&& obj.attr1.attr2&& obj.attr1.attr2.attr3&& obj.attr1.attr2.attr3.attr4 == 'constant' ) 返回;

我是否正确地认为每一层都需要单独测试,或者是否有语法快捷方式?

如果这是一次性的就没有问题,但这种结构渗透到我的代码中.



从答案来看,这是我的原位解决方案:

<前>尝试{如果(obj.attr1.attr2.attr3.attr4!='const')抛出'nada';}赶上(e){nonblockAlert('相关消息');返回;};

这是有效的,因为由于 attr 不存在而抛出的错误是由本地 throw() 捕获的.问题是语法不适合普通的 if then else 控件.

解决方案

正如人们所说,但没有人做过,你可以使用 try/catch:

尝试{if(obj.attr1.attr2.attr3.attr4 == 'constant') 返回;}赶上(e){}

这不是有史以来最好的代码,但它是最简洁、易读的.避免它的最好方法是不要将可能不存在的对象树嵌套得如此深.

for example, the following code

  if( obj.attr1.attr2.attr3.attr4 == 'constant' ) return;

needs to be rewritten as

  if( obj.attr1 
      && obj.attr1.attr2 
      && obj.attr1.attr2.attr3
      && obj.attr1.attr2.attr3.attr4 == 'constant' ) return;

am I correct in that each layer needs to be tested individually, or is there a syntactic shortcut for this?

if this were a one-shot would not be a problem, but this construct permeates my code.



from answers, here is the solution I have in situ:

try{ if( obj.attr1.attr2.attr3.attr4 != 'const' ) throw 'nada'; } catch(e){
    nonblockAlert( 'Relevant Message' );
    return;
};

this works since the error thrown for attr's non-existence is caught with the local throw(). the problem is the syntax does not fit in will with a normal if then else control.

解决方案

As people have mentioned, but nobody has done, you can use try/catch:

try {
    if(obj.attr1.attr2.attr3.attr4 == 'constant') return;
} catch(e) {}

It's not the best code ever, but it's the most concise, and easily readable. The best way of avoiding it would be not to have so deeply nested a tree of possibly-absent objects.

这篇关于在javascript中,是否有语法快捷方式检查嵌入对象的每一层是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 13:22:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410154.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快捷方式   是否存在   语法   对象   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!