【问题标题】:Why are identical objects from snapshot.before and snapshot.after, not equal? [duplicate]为什么来自 snapshot.before 和 snapshot.after 的相同对象不相等? [复制]
【发布时间】:2019-03-07 06:16:28
【问题描述】:

我有一个云函数来增加一个计数器,只有当快照中的某些字段发生变化时(在本例中为“练习”)。

在我的云功能中,我有一个总是因为某种原因触发的检查:

const before = snapshot.before.data();
const after = snapshot.after.data();     
if (before['exercises'] !== after['exercises']) {
   console.log(before['exercises']);
   console.log(after['exercises']);
   // Increment the counter...
}

并且日志语句是相同的:

[ { exerciseId: '-LZ7UD7VR7ydveVxqzjb',
    title: 'Barbell Bench Press' } ] // List of exercise objects

[ { exerciseId: '-LZ7UD7VR7ydveVxqzjb',
    title: 'Barbell Bench Press' } ] // Same list of exercise objects

我可以做些什么来确保快照中的这些值被视为平等?

谢谢。

【问题讨论】:

    标签: typescript google-cloud-firestore google-cloud-functions javascript-objects snapshot


    【解决方案1】:

    在 Javascript 中,对象是一种引用类型。如果你这样做:

    {a: 1} === {a: 1}
    

    这将是错误的,因为 Javascript 正在读取:

    ObjectReference1 === ObjectReference2

    你可以为determine the equality of two Javascript Objects 做一些事情,但如果你的对象那么小,我会做一个JSON.stringify 平等

    const before = {
      exerciseId: '-LZ7UD7VR7ydveVxqzjb',
        title: 'Barbell Bench Press' }
    
    const after = {
      exerciseId: '-LZ7UD7VR7ydveVxqzjb',
      title: 'Barbell Bench Press'
    };
    
    function areEqual(object1, object2) {
      return JSON.stringify(object1) === JSON.stringify(object2);
    }
    
    
    console.log(areEqual(before, after)); /// true

    【讨论】:

    • 谢谢,正是我需要的:)
    猜你喜欢
    • 1970-01-01
    • 2013-02-10
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2014-05-25
    • 1970-01-01
    相关资源
    最近更新 更多