为什么来自 snapshot.before 和 snapshot.after 的相同对象不相等?
Why are identical objects from snapshot.before and snapshot.after, not equal?
我有一个云函数来增加计数器,只有当快照中的某些字段发生变化时('exercises' 在这种情况下)。
在我的云函数中,我有这个检查总是出于某种原因触发:
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
如何确保快照中的这些值被视为相等?
谢谢。
在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
我有一个云函数来增加计数器,只有当快照中的某些字段发生变化时('exercises' 在这种情况下)。
在我的云函数中,我有这个检查总是出于某种原因触发:
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
如何确保快照中的这些值被视为相等?
谢谢。
在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