【问题标题】:How to find out if a variable exists or not in Dart如何在 Dart 中找出变量是否存在
【发布时间】:2019-11-14 08:01:45
【问题描述】:

在 JavaScript 中,我可以使用“in”运算符来检查变量是否存在。所以,也许这段代码可以正常工作。

index.html

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Using in operator</title>
 </head>
 <body>
  <div id="div1">hello</div>
  <script>
   document.someValue = "testValue";
   if( 'someValue' in document ) {
    document.getElementById('div1').innerHTML = document.someValue;
   }else{
    document.getElementById('div1').innerHTML = "not found";
   }
  </script>
 </body>
</html>

因此,div1 的最终内容将是“testValue”。 但是,Dart 没有“in”运算符。在 Dart 中,HtmlDocument 类确实有 contains() 方法。但是,该方法的参数类型是 Node,而不是 String。 我也试过这段代码。

print( js.context['document'] );
print( js.context['document']['someValue'] );

" js.context['document'] " 运行良好并返回 HtmlDocument 对象的实例。 但是,“ js.context['document']['someValue'] ”完全不起作用。这将不返回任何内容或不返回错误。

有没有办法检查 Dart 中的变量是否存在? :-(

感谢您的阅读!

【问题讨论】:

  • 这只是一个例子,还是你真的设置了document的属性?如果是这样,为什么?你的真正目标是什么?

标签: javascript dart


【解决方案1】:

没有简单的方法可以检查对象是否具有任意成员。

如果您希望 Dart 对象具有字段,您可能会这样做,因为您希望它实现具有该字段的接口。在这种情况下,只需检查类型:

if (foo is Bar) { Bar bar = foo; print(bar.someValue); }

Dart 对象的属性在创建后不会改变。要么有成员,要么没有,由类型决定。

如果您希望对象具有该成员,但您不知道声明该成员的类型(那么您可能正在做一些太棘手的事情,但是)那么您可以尝试在 try catch 中使用它.

var someValue = null;
try {
  someValue = foo.someValue;
} catch (e) {
  // Nope, wasn't there.
}

对于真正的探索性编程,您可以使用dart:mirrors 库。

InstanceMirror instance = reflect(foo);
ClassMirror type = instance.type;
MethodMirror member = type.instanceMembers[#someValue];
if (member != null && member.isGetter) {
  var value = instance.getField(#someValue).reflectee;  // Won't throw.
  // value was there.
} else {
  // value wasn't there.
}

【讨论】:

    【解决方案2】:

    我发现只需检查值是否为 null 就可以正常工作。

    if (js.context['document']['someValue'] != null) {
      // do stuff with js.context['document']['someValue']
    } else {
      // that property doesn't exist
    }
    

    【讨论】:

      【解决方案3】:

      假设你使用 dart:js 你可以使用JsObject.hasProperty

      js.context.hasProperty('someValue');
      

      【讨论】:

        猜你喜欢
        • 2023-03-20
        • 2012-11-10
        • 2010-10-25
        • 1970-01-01
        • 2015-12-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-30
        • 2012-07-05
        相关资源
        最近更新 更多