在 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 中的变量是否存在? :-(
感谢阅读!
最佳答案
没有简单的方法来检查对象是否具有任意成员。
如果您希望 Dart 对象有一个字段,您这样做可能是因为您希望它实现一个具有该字段的接口(interface)。在这种情况下,只需检查类型:
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.
}
关于javascript - 如何在 Dart 中判断一个变量是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22084452/