在javascript中,是否有语法快捷方式检查嵌入对象的每一层是否存在? [英] in javascript, is there syntatic shortcut checking existence of each layer of embedded object?

查看:28
本文介绍了在javascript中,是否有语法快捷方式检查嵌入对象的每一层是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如下面的代码

<前>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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆