Javascript !== return 为真,而 return 为假

Javascript !== returning true when should return false

我正在使用 Node.js 服务器和 async.js 来处理异步回调,以及 Mongo 连接到我的 Mongo 数据存储。我试图确定两个对象 _id 是否相等,如果相等,则执行一些代码。但是,比较未正确执行。这是代码:

async.forEachSeries(offerItem.offers, function(currentOfferItemOffer, callback) {
    Offer.findById(currentOfferItemOffer, function(err, offerItemOffer) {
        if (err) throw err;
        console.log(offerItemOffer._id) // 56953639ea526c8352081fdd
        console.log(offer._id)          // 56953639ea526c8352081fdd
        if (offerItemOffer._id !== offer._id) {
            console.log('offerItemOffer._id !== offer._id') // Is being logged even though it shouldn't

            ....

我很困惑为什么不能正确执行像这样的简单比较。当使用“===”检查两个 _id 是否相等时,代码会按预期运行——但这在逻辑上是不正确的,因为只有在 _id 不相等时才应执行下一个块。任何想法将不胜感激。谢谢!

_id 上使用 toString() 方法。

if (offerItemOffer._id.toString() !== offer._id.toString()) {//...

console.log() 调用 toString() 所以看起来输出是相同的,因为它被转换为字符串。

看起来 _id 是对象,而不是字符串。在这种情况下它们仍然是两个不同的对象。你应该这样做:

JSON.stringify(offerItemOffer._id) !== JSON.stringify(offer.-id) 

将它们作为字符串进行比较。

这里有更多内容Object comparison in JavaScript

JavaScript 有两种不等式运算符。即 !=!==.

!= 在比较之前对运算符调用字符串化。这意味着比较时不考虑给定运算符的 type/class。

!== 不调用 stringfy。这意味着考虑了运算符的 type/class。

这就是为什么下面的句子会产生不同的输出

'1' != 1   // -> false (they are equal since what's being compared is '1' != '1'
'1' !== 1  // -> true  (they are different since what's being compared is a string with an integer)

因此,您可以通过使用 != 运算符忽略对象 types/classes 来解决您的问题。