samedi 4 avril 2015

changing value of local variable perform change in value of original global variable

In my node js program in routes i have created array named list. I have assigned value to array from function declared in model. Code for route is:



var express = require('express');
var router = express.Router();
var questionModel = require('../model/questionModel');
var userModel=require('../model/userModel');

/* GET home page. */
router.get('/', function(req, res, next) {



//declare an array and store the json data
var list=questionModel.getAllQuestions();

for(i=0;i<list.length; i++){
console.log(list[i].submitter);
console.log(userModel.getUserById(list[i].submitter)[0]);
list[i].submitter=userModel.getUserById(list[i].submitter)[0].fname;
}
console.log(list);
//respond with the array
res.json(list);

//res.redirect("../question/" + this_id);

});

module.exports = router;


Here in module i am using local variable as in this class project i am not using any database. My all Models fetch value from one global variable.


This code is work fine on first request. But on first request changing value of list[i].submitter locally value of global value change.


Change in global value creates problem when i get second request. On second request value return from questionModel.getAllQuestions is unnecessarily updated.


Aucun commentaire:

Enregistrer un commentaire