【发布时间】:2019-12-26 17:52:49
【问题描述】:
我不知道为什么当我更改作为另一个 var 副本的变量时,两者都被更改了?这对我来说没有任何意义吗?
你能解释一下为什么吗?这是我第一次在 node js 中遇到这种反应,我在使用 Pointers 时在 C 或 C++ 中知道这一点,但在 node js 中我不知道为什么!
function getByType(where) {
var object = {
topMarque: null,
posModel: null,
};
var countPer = "titre";
var copywhere = where;
if (where.categorie == "voiture") {
countPer = "marqueNom";
copywhere.marqueId = {
[Op.ne]: null
}
} else {
console.log("------------------------------------------");
console.log(where)
console.log("------------------------------------------");
copywhere.titre = (where.titre) ? where.titre : {
[Op.ne]: null
}
console.log("******************************************");
console.log(where)
console.log("******************************************");
}
return db.stats.findAll({
attributes: [countPer, [db.sequelize.fn('COUNT', db.sequelize.col(countPer)), 'total']],
group: [countPer],
limit: 5,
where: copywhere,
order: [
[db.sequelize.fn('COUNT', db.sequelize.col(countPer)), 'DESC'],
],
}).then(function(count) {
object.topMarque = count;
return db.stats.findAll({
attributes: ['pos', [db.sequelize.fn('COUNT', db.sequelize.col('pos')), 'total']],
group: ['pos'],
where: where
}).then(function(countPosCu) {
object.posModel = countPosCu;
return Promise.resolve(object);
});
}).catch(error => {
return Promise.resolve(object);
})
}
在第一个日志中我有这个:
------------------------------------------
{ categorie: 'moto' }
------------------------------------------
在第二个日志中我有这个:
******************************************
{ categorie: 'moto', titre: { [Symbol(ne)]: null } }
******************************************
【问题讨论】:
-
因为您没有复制任何内容,所以您引用了相同的符号。与 C 或 C++ 中的方法相同:如果您有一个对象的引用,如果您更改该对象,任何具有相同引用的东西都会看到这些更改。如果你想要一个新对象,那么你需要克隆它(并注意深克隆与浅克隆,也与 C 或 C++ 相同)。
-
具体来说,
copywhere = where不会复制对象。 -
感谢您的回复,所以您告诉我,当我制作 var copywhere = where 时,它不是新对象或新变量,它与原来的 where 相同,非常感谢您的解释。
-
与 C 或 C++ 指针相同——它只是引用相同的东西。
-
@DaveNewton 非常感谢你,我以前不知道,我会审查我的代码以避免引用,再次感谢你的解释。
标签: javascript node.js api express sequelize.js