【问题标题】:Javascript !== returning true when should return false [duplicate]Javascript!==在应该返回false时返回true [重复]
【发布时间】:2016-01-13 03:00:10
【问题描述】:

我使用 Node.js 服务器和 async.js 处理异步回调,以及 Mongoose 连接到我的 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 不相等时才应执行下一个块。任何想法将不胜感激。谢谢!

【问题讨论】:

  • 你确定你没有真正的 Mongo objectID,也没有十六进制字符串,你用typeof检查了这些 ID
  • 看起来像对象,而不是字符串。
  • offerItemOffer._id.toString() 应该解决它
  • 工作就像一个魅力。谢谢!

标签: javascript node.js mongodb mongoose async.js


【解决方案1】:

_id 上使用toString() 方法。

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

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

【讨论】:

  • 是的,做到了。谢谢!
【解决方案2】:

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

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

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

更多Object comparison in JavaScript

【讨论】:

    【解决方案3】:

    JavaScript 有两种类型的不等式运算符。即!=!==

    != 在比较之前对运算符调用 stringify。这意味着在比较时不考虑给定运算符的类型/类。

    !== 不调用 stringfy。这意味着要考虑运算符的类型/类。

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

    '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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-28
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      相关资源
      最近更新 更多