将对象推送到Node.js中的全局声明的数组中

时间:2017-06-01 01:13:10

标签: javascript 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 []

2 个答案:

答案 0 :(得分:4)

您必须将要推送的对象作为参数传递给数组:

global.arrayOfObjects.push(new test(123));

Array.prototype.push() documentation

答案 1 :(得分: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