我在节点中编写一个简单的应用程序,但是在引用来自不同模块的对象时遇到了问题。对象构造函数和方法是(我跳过一些方法来保持摘录简短):
function Account (name, password) {
this._name = name;
this._password = password;
this._attributes = [];
}
Account.prototype.load = function (id) {
var self = this;
self = db.loadObject(id, 'account'); // separate module to save/retrieve data
this._name = self._name;
this._password = self._password;
this._attributes = self._attributes;
return this;
};
Account.prototype.getAttributes = function () {
return this._attributes;
}
Account.prototype.addAttributes = function (a) {
this._attributes.push(a);
};
module.exports = Account;
db模块在这一点上并不花哨:
var fs = require('fs');
var paths = {
'account' : './data/accounts/'
};
function loadObject (name, type) {
var filePath = paths[type] + name + '.json';
if (!fs.existsSync(filePath)) {
return false;
}
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
};
function saveObject (object, type) {
fs.writeFileSync(paths[type] + object.getName() + '.json', JSON.stringify(object),'utf8');
};
exports.loadObject = loadObject;
exports.saveObject = saveObject;
文件保存为:
{"_name":"John","_password":"1234","_attributes":[["Jane","sub",[[10,1]]]]}
在我的调用者模块上,我尝试检索属性:
var Account = require('./account.js');
var account = new Account();
...
account.load(name);
...
var attr = account.getAttributes();
for (var item in attr) {
console.log(item[0]);
};
...
在上面的代码中,最后一个循环打印未定义的对象。我检查了文件,信息保存和加载没有任何问题。数组attr不为空。如果我打印它:
util.log(typeof attr+': '+attr);
我明白了:
object: Jane,sub,10,1
实例问题?我应该重写_attributes直接通过account.attributes访问吗?
答案 0 :(得分:1)
这是您目前输出数据的代码:
var attr = account.getAttributes();
for (var item in attr) {
console.log(item[0]);
};
此代码执行的操作是将_attributes
字段中每个键的第一个字符输出到控制台。根据您在问题中显示的数据,此输出的结果为0
,因为您的_attributes
字段具有此值:[["Jane","sub",[[10,1]]]]
。在var item in attr
中使用时,item
变量只会获得字符串"0"
的一个值,而item[0]
也会计算为字符串"0"
。我实际上已经将你的代码和数据剪切并粘贴到文件中并运行你的代码来仔细检查这一点,这确实是我运行代码时得到的。我没有得到未定义的值。从数组中获取值的更合理的方法是:
var attr = account.getAttributes();
for (var item in attr) {
console.log(attr[item]);
}
如果你想迭代两个级别:
for (var item in attr) {
var value = attr[item];
for (var item2 in value) {
console.log(value[item2]);
}
}