gpt4 book ai didi

javascript - 为什么比较结果不一样?

转载 作者:行者123 更新时间:2023-11-29 10:31:36 24 4
gpt4 key购买 nike

这是 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

最佳答案

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

关于javascript - 为什么比较结果不一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44779455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com