为什么在使用 Spidermonkey 时我得到的输出是 [object Object] 而不是 [Id: id_value]

Why am i getting output as [object Object] instead of [Id: id_value] when using Spidermonkey

我在 mac 终端上使用 vi 编辑器并编写了一些 Javascript 代码。当我在这段代码上使用 Spidermonkey 引擎 运行 时:

function getPerson(id) {
  if (id < 0) {
    throw new Error('ID must not be negative: '+id);
  }
  return { id: id };
}

function getPersons(ids) {
  var result = [];
  ids.forEach(function (id) {
    try {
      var person = getPerson(id);
      result.push(person);
    } catch (exception) {
      print(exception);
  }
});
return result;
}

当我运行以下命令时:

js -f exc.js -i
js> getPersons([1,-2,3]);

我收到以下回复:

Error: ID must not be negative: -2
[object Object],[object Object]

而不是:

Error: ID must not be negative: -2
{ id: 1 }, { id: 3 }

那么,我该如何纠正这个问题?

如果您可以控制打印对象的位置,请尝试在打印之前对对象使用 JSON.stringify

可能这可行(未测试):

js> JSON.stringify(getPersons([1,-2,3]));

JSON 与其他答案一样,通常是细读简单对象内容的一种有用且快速的方法。但是如果你想自定义每个对象的输出(例如当使用复杂对象、工厂、类...),或者如果你想直接使用 console.log,你应该实现 toString() 方法:

var person = {
  id: 123,
  toString: function() {
    return '[Id: ' + this.id + ']'
  }
};

person
//=> [Id: 123]

请注意,JS shells 的行为各不相同。例如,虽然您的 JS shell 似乎调用 toString() 来打印值(默认 toString() 实现 returns [object Object]),但 Node.js 将具有"more helpful" 行为类似于 pretty-printing 对象和变量以及 native-looking 方式的函数:

> console.log(person)
{ id: 123 }

即使是我本地版本的 SpiderMonkey 也有与您不同的行为:

js> person
({id:123})

所以不要依赖这个输出来获得任何可靠的结果。如果你想要在 SpiderMonkey 中隐式且可靠地调用 toString() 的东西,请使用旧的字符串强制转换:

js> ''+person
"[Id: 123]"

print()函数:

js> print(person)
[Id: 123]