2017-06-01 45 views
0

我從來沒有在Node.js中使用過全局變量,因此我無法理解爲什麼這不起作用。我聲明全局變量是數組,比我想推入一些對象,爲了調試我只是想把它串起來。 我試着這樣說:在Node.js中將對象推入全局聲明的數組

var test = require('./api/test'); //my class 
global.arrayOfObjects = []; //declaring array 
global.arrayOfObjects.push = new test(123); //docs3._id is something I return from db 
console.log(JSON.stringify(global.arrayOfObjects)); //I get [] 
+3

你爲什麼要重新定義'.push'屬性爲一個新的對象?你是否打算調用'.push()'方法? – jfriend00

回答

0

必須這樣做,三選一,你是混入兩個:

var test = require('./api/test'); 
//global.arrayOfObjects = []; not need to declare the var here 
global.arrayOfObjects = new test(123); from db 
console.log(JSON.stringify(global.arrayOfObjects)); 

var test = require('./api/test'); 
global.arrayOfObjects = []; //needed to declare with this option 
global.arrayOfObjects.push(1); 
global.arrayOfObjects.push(2); 
global.arrayOfObjects.push(3); 
console.log(JSON.stringify(global.arrayOfObjects)); 

global.arrayOfObjects.push(new test(123)); // I think this is the best option 
+0

爲什麼分配'global.arrayOfObjects = []',然後立即分配相同的變量別的東西? – jfriend00

+0

@ jfriend00我真的不建議它......但是OP想要......也許我會用觀察更新答案,謝謝 –

+0

@ jfriend00我認爲現在更好,你不覺得嗎? –