为什么我的副本变量会在节点js中更改原始值变量?

时间:2019-12-26 17:52:49

标签: javascript node.js api express sequelize.js

我不知道为什么当我更改另一个var的副本的变量时,两个变量都被更改了?这对我来说没有任何意义?

您能解释一下为什么吗?这是我第一次在node js中遇到这种反应,我在使用Pointer时在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 } }
******************************************

1 个答案:

答案 0 :(得分:0)

如果您正在使用javascript处理对象或数组,则无论您是否将数组/对象复制到另一个变量中,它都将引用相同的引用。

请检查以下示例:

// Declaring Array
var arr1 = [1,2,3,4,6];

//Trying to copy array into another variable
var arr2 = arr1;
console.log("========================");
//Display Array one
console.log(arr1);
//Adding more value in arra1
arr1.push(10);
arr1.push(11);
console.log("========================");
////Display Array Two
console.log(arr2);
console.log("========================");

O / P:

========================
[ 1, 2, 3, 4, 6 ]        
======================== 
[ 1, 2, 3, 4, 6, 10, 11 ]
======================== 

如上例所示,我们声明一个数组并将其复制到另一个数组中,然后在 arr1 内推入两个数组,并显示 arry2 将显示引用 arr1

的数组值