类类型对象未在node.js中跨模块返回值

Class-type object not returning values across module in node.js

本文关键字:模块 返回值 js node 类型 对象      更新时间:2023-09-26

我正在节点中编写一个简单的应用程序,但在引用来自不同模块的对象时遇到了问题。对象构造函数和方法是(为了简短摘录,我跳过了一些方法):

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;

数据库模块在这一点上并不花哨:

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]);
};
...

在上面的代码中,最后一个循环打印未定义的对象。我已经检查了文件,信息被保存和加载,没有任何问题。数组属性不为空。如果我使用以下内容打印:util.log(typeof attr+': '+attr);我得到:object: Jane,sub,10,1

实例问题?我是否应该重写要通过account.attributes直接访问的_attributes?

这是您当前用于输出数据的代码:

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]);
    }
}