我有一个对象的ListModel,它可能带有或不带有myvis参数(用于可见性)。如果myvis === true,则ListView委托应该可见。如果未定义myvis,我想假设myvis === true

为了检查myvis是否已定义和/或存在,我尝试了3种方法:


return (typeof myvis) === 'undefined' ? true : myvis
return myvis === null ? true : myvis
return hasOwnProperty("myvis") ? myvis : true


没有一个是成功的。请参阅下面的代码输出

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    ListModel {
        id: myjson
        ListElement {
            displayName: "Planes"
            myvis: false
        }
        ListElement {
            displayName: "Trains"
            myvis: true
        }
        ListElement {
            displayName: "Automobiles"
        }
    }


    ListView {
        model: myjson
        anchors.fill: parent

        delegate: Text {
            text: displayName
            visible: {
                console.log("typeof " + displayName + ":myvis is " + (typeof myvis))
                console.log("hasOwnProperty " + hasOwnProperty("myvis"))
                console.log(displayName + " is " + myvis)

                //if myvis is not defined, assume it to be TRUE
                return (hasOwnProperty("myvis") ? myvis : true)
            }
        }
    }
}


我得到的输出:

qml: typeof Planes:myvis is boolean
qml: hasOwnProperty false
qml: Planes is false
qml: typeof Trains:myvis is boolean
qml: hasOwnProperty false
qml: Trains is true
qml: typeof Automobiles:myvis is boolean
qml: hasOwnProperty false
qml: Automobiles is false


我期望的输出:

qml: typeof Planes:myvis is boolean
qml: hasOwnProperty true
qml: Planes is false
qml: typeof Trains:myvis is boolean
qml: hasOwnProperty true
qml: Trains is true
qml: typeof Automobiles:myvis is undefined
qml: hasOwnProperty false
qml: Automobiles is undefined


编辑
如果模型是JSON对象且不是QML,则可以使用:

    property var myjson: [
        {
            displayName: "planes",
            myvis: false
        },
        {
            displayName: "trains",
            myvis: true
        },
        {
            displayName: "automobiles"
        }
    ]

    ListView {
        model: myjson
        anchors.fill: parent

        delegate: Text {
            text: modelData.displayName
            visible: {
                console.log("typeof " + modelData.displayName + ":myvis is " + (typeof modelData.myvis))
                console.log("hasOwnProperty " + modelData.hasOwnProperty("myvis"))
                console.log(modelData.displayName + " is " + modelData.myvis)

                //if myvis is not defined, assume it to be TRUE
                return (modelData.hasOwnProperty("myvis") ? modelData.myvis : true)
            }
        }
    }


输出完全符合预期。有没有办法在保留ListModel和ListElements的同时获取此输出?

最佳答案

如果只设置myvis !== false会发生什么,我认为这就是您要寻找的。如果它不等于false,则只需要显示您的东西即可。

关于javascript - 如何检查JSON对象参数是否存在?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59416506/

10-13 01:08