对 Javascript 对象的 console.log 的澄清
Clarification on a console.log of a Javascript object
这似乎是基本的,但我遗漏了一些东西。我正在使用 node.js 强大的模块,并在控制台记录错误,如:
uploadProc.on('error', function(err) {
console.log("Form upload error...");
console.log(typeof err);
console.log(err);
console.log(err[0]);
console.log(err['Error']);
console.log(JSON.stringify(err);
});
输出为:
object
[Error: Request aborted]
undefined
undefined
{}
如我所见,它既不是数组也不是具有 属性 错误的常规对象。如果我想对它进行字符串化,无论它是什么类型,我该怎么做?可能是字符串开始。但如果是这样的话,typeof 会返回 "string." 我在 Mozilla 上检查了这个。似乎属于 "any other object" 类别。有人可以解释控制台记录为 [Error: Request aborted] 的对象类型是什么吗?
这是一个 Error object:
> new Error('hello world') instanceof Error
true
它有一个 .toString()
方法,您可以使用它来对其进行字符串化:
> console.log(new Error('hello world').toString())
Error: hello world
或者,如果您想输出堆栈跟踪:
> console.log(new Error('hello world').stack)
Error: hello world
at repl:1:13
at REPLServer.defaultEval (repl.js:262:27)
at bound (domain.js:287:14)
at REPLServer.runBound [as eval] (domain.js:300:12)
at REPLServer.<anonymous> (repl.js:431:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:211:10)
at REPLServer.Interface._line (readline.js:550:8)
at REPLServer.Interface._ttyWrite (readline.js:827:14)
这似乎是基本的,但我遗漏了一些东西。我正在使用 node.js 强大的模块,并在控制台记录错误,如:
uploadProc.on('error', function(err) {
console.log("Form upload error...");
console.log(typeof err);
console.log(err);
console.log(err[0]);
console.log(err['Error']);
console.log(JSON.stringify(err);
});
输出为:
object
[Error: Request aborted]
undefined
undefined
{}
如我所见,它既不是数组也不是具有 属性 错误的常规对象。如果我想对它进行字符串化,无论它是什么类型,我该怎么做?可能是字符串开始。但如果是这样的话,typeof 会返回 "string." 我在 Mozilla 上检查了这个。似乎属于 "any other object" 类别。有人可以解释控制台记录为 [Error: Request aborted] 的对象类型是什么吗?
这是一个 Error object:
> new Error('hello world') instanceof Error
true
它有一个 .toString()
方法,您可以使用它来对其进行字符串化:
> console.log(new Error('hello world').toString())
Error: hello world
或者,如果您想输出堆栈跟踪:
> console.log(new Error('hello world').stack)
Error: hello world
at repl:1:13
at REPLServer.defaultEval (repl.js:262:27)
at bound (domain.js:287:14)
at REPLServer.runBound [as eval] (domain.js:300:12)
at REPLServer.<anonymous> (repl.js:431:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:211:10)
at REPLServer.Interface._line (readline.js:550:8)
at REPLServer.Interface._ttyWrite (readline.js:827:14)