为什么比较结果不一样?

时间:2017-06-27 11:44:22

标签: javascript qt qml

这是关于QML的功能。目前尚不清楚为什么比较结果不同?

...
function someFunction() {
        var id1 = AAAAA.objectId // it is QByteArray property of C++ object
        var id2 = BBBBB.objectId // it is QByteArray property of C++ object
        var isEqual = id1 === id2
        var isEqualToString = id1.toString() === id2.toString()

        console.log("=============================")
        console.log("id1: ", id1)
        console.log("id2: ", id2)
        console.log("isEqual: ", isEqual)
        console.log("id1.toString(): ", id1.toString())
        console.log("id2.toString(): ", id2.toString())
        console.log("isEqualToString: ", isEqualToString)
}
...

控制台结果:

id1:  2607d35d-d9d0-49af-b944-3fc60993890a
id2:  2607d35d-d9d0-49af-b944-3fc60993890a
isEqual:  false
id1.toString():  2607d35d-d9d0-49af-b944-3fc60993890a
id2.toString():  2607d35d-d9d0-49af-b944-3fc60993890a
isEqualToString:  true

1 个答案:

答案 0 :(得分:3)

id1id2是javascript object

console.log("typeof id1: ", typeof id1)
console.log("typeof id2: ", typeof id2)

输出:

qml: typeof id1:  object
qml: typeof id2:  object

在javascript中,类型object的2个变量等于当且仅当它们代表同一个对象时。 (在C ++中,它就像比较指针一样,如果它们指向相同的地址,它们就相等)。

知道了这一点,我们可以再看看你的代码:

var id1 = AAAAA.objectId // Creates an object and reference it by id1
var id2 = BBBBB.objectId // Creates of another object and reference it by id2
var isEqual = id1 === id2 // false because id1 and id2 reference 2 different objects, regardless of their content
var isEqualToString = id1.toString() === id2.toString() // true because you compare strings and strings are compared using their content