如何找出Dart中是否存在变量

Saf*_*Pin 4 javascript dart

在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>
Run Code Online (Sandbox Code Playgroud)

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

print( js.context['document'] );
print( js.context['document']['someValue'] );
Run Code Online (Sandbox Code Playgroud)

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

有什么方法可以检查Dart中变量的存在吗?:-(

感谢您的阅读!

lrn*_*lrn 6

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

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

if (foo is Bar) { Bar bar = foo; print(bar.someValue); }
Run Code Online (Sandbox Code Playgroud)

Dart对象创建后,其属性不会更改。它具有成员,也可以没有成员,由类型确定。

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

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

对于真正的探索性编程,您可以使用该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.
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*uin 1

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

js.context.hasProperty('someValue');
Run Code Online (Sandbox Code Playgroud)