我用下面的函数来比较两个相等的值(如在控制台中显示的,但是返回是假的.
function removeGroup(req, res, next) {
const user = req.user;
const found = user.groups.some((obj, idx) => {
console.log('obj._id: ', obj._id);
console.log('req.params.groupId: ', req.params.groupId);
if (obj._id === req.params.groupId) {
console.log('equal');
user.groups.splice(idx, 1);
return true;
}
console.log('not equal');
return false;
});
if (found) {
user.save()
.then(savedTable => res.json(savedTable))
.catch(e => next(e));
} else {
res.status(404);
res.json({ message: 'Group Not Found' });
}
}以下是控制台.log结果
obj._id: 59109bc44ea63331151b9327
req.params.groupId: 59109bc44ea63331151b9327
not equal发布于 2017-05-09 16:58:24
JavaScript中的一个好做法是始终使用===而不是==来避免强制(隐式类型转换)。为了记录在案,您还可以在Object.is()中使用ES6.
那么,为什么您的代码不能工作呢?很难断言,因为你在问题中没有提供足够的细节,但从我在评论中看到的,我想你会发现下面有一个明确的解释:
obj._id和req.params.groupId在值、和类型方面必须严格相等。这对于原始值(字符串、数字、布尔值、.)是很好的,但问题是,在JavaScript中,您不能比较这样的对象。在这种语言中,对象通过引用进行比较。这意味着,如果一个对象不是同一个实例,即使它具有完全相同的属性,它也永远不会与另一个对象相等。
let ref = {};
// false
console.log({} == {});
console.log({} === {});
console.log(Object.is({}, {}));
// true
console.log(ref == ref);
console.log(ref === ref);
console.log(Object.is(ref, ref));
https://stackoverflow.com/questions/43853025
复制相似问题