即使日志显示,Sails.js应用程序variables数据也不会显示在视图中

我有一个简单的销售应用程序,在控制器中查询数据库。 检索结果,使用async.each函数对数据进行一些操作,然后将数组发送到视图。

即使我的日志显示数组中的数据,我的视图正在接收一个空白数组。

"index": function(req, res, next) { Sales.find().sort("createdAt DESC").done(function(err, sales) { if (err) { res.send("An error has occured. :("); } else { if (!sales) { req.session.flash = { err: { message: "You have no billing as of now.", style: "alert-info" } } } else { var bills = []; async.eachSeries(sales, function(thisSale, callback) { if (!bills[thisSale.billingNo]) { bills[thisSale.billingNo] = { id: thisSale.billingNo, createdAt: thisSale.createdAt, total: (thisSale.quantity * thisSale.price), location: thisSale.location, }; } else { bills[thisSale.billingNo].total += (thisSale.quantity * thisSale.price); } callback(); }, function(err) { if (err) { console.log('Something went wrong !'); exit(); } else { res.send({ billing: bills }); console.log("=====\nBILL\n=====\n", bills); } }); } } }); }, 

我用res.sendreplaceres.view来debugging我的代码,在客户端我只收到这个:

 { "billing": [] } 

虽然控制台日志显示:

 ===== BILL ===== [ '53b95fdc1f7a596316f37af0': { id: '53b95fdc1f7a596316f37af0', createdAt: Sun Jul 06 2014 20:10:28 GMT+0530 (IST), total: 6497, location: 'Location A' }, '53b8f7c81f7a596316f37aed': { id: '53b8f7c81f7a596316f37aed', createdAt: Sun Jul 06 2014 12:46:24 GMT+0530 (IST), total: 6497, location: 'Location A' } ] 

有人能帮我弄清楚我做错了什么吗?

我试图debugging的问题,发现我无法访问账单[0],然后使用forEach循环的数组帐单,发现它无法运行每个循环。

在将variables账单从一个数组更改为一个对象时,问题得到解决。

我不完全确定为什么会发生这种情况,或者为什么我无法将variables添加到一个数组,但改变

 var bills = []; 

 var bills = {}; 

解决了这个问题。

也许你来自PHP背景,“关联数组”是一个有效的types? 在Javascript中,数组只能被整数索引,例如

 bills[0] = "something"; 

这与Javascript数组像所有非原始types的对象实例一样 ,使得它们可以添加任意属性这一事实有些混淆:

 bills.abc = 123; bills["some arbitrary string"] = 555; 

但是你坚决不鼓励这样使用数组,原因很多,包括:

  • JSON.stringify()会忽略非整数索引,这就是为什么你在问题中遇到问题。 Sails(以及许多其他库)使用JSON.stringify()来序列化Javascript对象进行传输。
  • Javascript数组有几个保留键,例如lengthpushpop ,你不能赋值。
  • 数组的length()方法不会计算非整数键。
  • 用这种方式处理数组只是令人困惑; 这就是简单的对象(用{}声明)是什么!

希望这可以解释为什么改变为var bills = {}使一切正常。