我使用 node.js 和 express。
我在“ req.session
”上保存了一个包含对象数组的复杂对象。此外,我保存对数组中一个对象的引用。例如:
var value = {
name: "name"
, values: []
};
req.session.value = value;
//
// I populate 'req.session.value' with values (with the same structure)
//
// then I save reference to one of the inner objects
var currentValue = req.session.value[3];
//
// later I try to change the save object
//
currentValue.name = "newName";
我预计如果我更改 ' currentValue
' 那么 ' req.session.value[3]
' 也会更改。但是,由于某种原因,它没有发生。
具体来说,如果我currentValue
在分配后立即更改它,那么它req.session.value[3]
就会改变,但如果我在下一次调用中这样做,那么只是currentValue
改变了。
在示例中:我对“ req.session
”中的“ app.get(...)
”进行分配,如果我更改“”中的值,currentValue
它app.get(...)
运行正常(两个地方的值都更改)但是如果我在“ app.post(...)
”中更改它,唯一的改变的对象是currentValue
whilereq.session.value[3]
左相同的。
提前谢谢
,
编码:
'app.get("/template/:templateid/feature/add", isTemplate, function(req, res) {'
' if (!req.session.features) { // if features empty'
''
' // Save the first features level from the current template in the session '
' req.session.features = req.session.template.feature;'
' //'
' if (!req.session.featureNodes) { // featureNotes is a stack/branch of the features'
' req.session.featureNodes = [];'
' }'
' if (!req.query.featureroot || req.query.featureroot == "") {'
' } else {'
' var featureRoot = getFeature(req.query.featureroot, req.session.features); // get one object from req.session.features'
' if (featureRoot) {'
' req.session.featureNodes.push(featureRoot); // save reference'
' var featureR = req.session.featureNodes.pop(); // do check that work!'
' var values = {'
' name: "req.body.name"'
' , description: "req.body.description"'
' , wieght: "req.body.wieght"'
' , created: new Date()'
' , modified: new Date()'
' , feature: []'
' };'
''
' featureR.feature.push(values); // also req.session.features changed'
' req.session.featureNodes.push(featureRoot); // push the reference back for use later'
' } '
' }'
' res.render("addfeature2template.jade", { '
' title: "Add new feature"'
' ,template: req.session.template'
' ,feature: req.session.featureNodes'
' });'
'});'
''
'app.post("/feature/add", isUser, function(req, res) {'
' var SUBMIT = "Create";'
' var CANCEL = "Cancel";'
' switch ( req.param("feature") ) {'
' case SUBMIT:'
' var fields = { name: 1, description: 1, wieght: 1};'
' var values = {'
' name: req.body.name'
' , description: req.body.description'
' , wieght: req.body.wieght'
' , created: new Date()'
' , modified: new Date()'
' , feature: []'
' };'
' if (req.session.featureNodes.length < 1) {'
' req.session.features.push(values);'
' } else {'
' var featureRoot = req.session.featureNodes.pop(); // pop the reference'
' featureRoot.feature.push(values); // change the object but the req.session.features didnt changed '
' }'
' req.session.template = template;'
' res.redirect("/template/" + req.body.templateid);'
' break;'
' case CANCEL:'
' res.redirect("/template/" + req.body.templateid);'
' break;'
' }'
'});'