怎样在 QML 中检查属性是否未定义?
这是我所尝试的:
这是我所尝试的:
Button {
id: myButton
text: if (text === "undefined"){"default text"}
}
Button {
id: myButton
text: if (text === "undefined"){"default text"}
}
text: text ? text : "默认文本"
"undefined"
只是一个字符串表示,表示没有引用任何东西,就像其他语言中的None
或NULL
一样。
===
是严格比较运算符,您可能想阅读这个线程:https://stackoverflow.com/questions/523643/difference-between-and-in-javascript。import QtQuick 2.3
import QtQuick.Controls 1.2
Button {
id: myButton
text: text ? text : "default text"
}
QML Button: Binding loop detected for property "text"
text
更改为modelText
会导致错误。ReferenceError: modelText is not defined
import QtQuick 2.3
import QtQuick.Controls 1.2
Button {
id: myButton
text: "default text"
Component.onCompleted: {
if (modelText !== "undefined") {
myButton.text = modelText;
}
}
}
typeof
typeof
运算符会静默处理错误并按预期工作。
import QtQuick 2.3
import QtQuick.Controls 1.2
Button {
id: myButton
text: "default text"
Component.onCompleted: {
if (typeof modelText !== "undefined") {
myButton.text = modelText;
}
}
}
text === undefined
。如果text
是null
,则此语句将计算为false。undefined
和null
),请将其用作if语句或三元运算符中的条件。如果您需要将比较结果存储为布尔值,请使用var textPresent = !!text
(尽管双重!
可能会让阅读代码的人感到困惑)。
object
未定义时评估为false。类似于C语言中的if(pointer),当指针的值为0(NULL)时评估为false。值得注意的是,用于按钮文本属性的text
变量来自外部作用域。使用text: inText ? inText : "默认文本"
或者if(inText) {文本} else {"默认文本"}
会更清晰明了。 - Kissiel如果(文本为真)则 {文本 = 文本} 否则 {文本 = "默认文本"}
-- 这个准确吗? - Anonif (text is true)
。我觉得更容易理解为if (text *is*)
或者if (text exists)
。 另外一个好的参考来源是:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined - Kissiel