当我在JavaScript程序中使用console.log()
输出一个对象时,我只会看到输出[object Object]
,这对于找出是什么对象(甚至是什么类型的对象)并不是很有帮助。
在C#中,我习惯于重写ToString()
以便能够自定义对象的调试器表示。在JavaScript中是否有类似的方法?
当我在JavaScript程序中使用console.log()
输出一个对象时,我只会看到输出[object Object]
,这对于找出是什么对象(甚至是什么类型的对象)并不是很有帮助。
在C#中,我习惯于重写ToString()
以便能够自定义对象的调试器表示。在JavaScript中是否有类似的方法?
toString
方法。 请参见以下示例:
function Foo() {}
// toString override added to prototype of Foo class
Foo.prototype.toString = function() {
return "[object Foo]";
}
var f = new Foo();
console.log("" + f); // console displays [object Foo]
参见此讨论,学习如何在JavaScript中确定对象类型名称。
toString
属性,但Object.prototype.toString.call(f)
仍将显示[object Object]
。 - Frederik Krautwald为你的对象或原型编写toString
的重写方法:
var Foo = function(){};
Foo.prototype.toString = function(){return 'Pity the Foo';};
var foo = new Foo();
然后将其转换为字符串以查看对象的字符串表示:
//using JS implicit type conversion
console.log('' + foo);
如果你不喜欢多余的打字,你可以创建一个函数,将其参数的字符串表示记录到控制台:
var puts = function(){
var strings = Array.prototype.map.call(arguments, function(obj){
return '' + obj;
});
console.log.apply(console, strings);
};
使用方法:
puts(foo) //logs 'Pity the Foo'
puts(foo, [1,2,3], {a: 2}) //logs 'Pity the Foo 1,2,3 [object Object]'
E2015提供了更好的语法,但是你需要使用像Babel这样的转译器:
// override `toString`
class Foo {
toString(){
return 'Pity the Foo';
}
}
const foo = new Foo();
// utility function for printing objects using their `toString` methods
const puts = (...any) => console.log(...any.map(String));
puts(foo); // logs 'Pity the Foo'
如果你正在使用Node,考虑使用util.inspect
可能是值得的。
var util = require('util')
const Point = {
x: 1,
y: 2,
[util.inspect.custom]: function(depth) { return `{ #Point ${this.x},${this.y} }` }
}
console.log( Point );
这将产生:
{ #Point 1,2 }
没有 inspect 版本打印的是:
{ x: 1, y: 2 }
更多信息(+在类
中使用的示例):
给自定义对象或类添加'Symbol.toStringTag'属性。
分配给它的字符串值将成为其默认字符串描述,因为它在内部被Object.prototype.toString()
方法访问。
例如:
class Person {
constructor(name) {
this.name = name
}
get [Symbol.toStringTag]() {
return 'Person';
}
}
let p = new Person('Dan');
Object.prototype.toString.call(p); // [object Person]
class Person {
constructor(name) {
this.name = name
}
get[Symbol.toStringTag]() {
return 'Person';
}
}
let p = new Person('Dan');
console.log(Object.prototype.toString.call(p));
一些JavaScript类型(例如Maps和Promises)已定义了内置的toStringTag
符号
Object.prototype.toString.call(new Map()); // "[object Map]"
Object.prototype.toString.call(Promise.resolve()); // "[object Promise]"
由于Symbol.toStringTag
是一个众所周知的符号,我们可以引用它并验证上述类型确实具有Symbol.toStringTag属性 -
new Map()[Symbol.toStringTag] // 'Map'
Promise.resolve()[Symbol.toStringTag] // 'Promise'
toString()
一起实现 function MyObj() {} Object.prototype.toString.call(new MyObj()) // "[object MyObj]"
的唯一方法吗? - tonix在浏览器JS中获取可调试的输出的简单方法是将对象序列化为JSON。因此,您可以进行如下调用:
console.log ("Blah: " + JSON.stringify(object));
以一个例子来说,alert("Blah! " + JSON.stringify({key: "value"}));
会产生一个带有文本内容 Blah! {"key":"value"}
的警告框。
使用模板字符串:
class Foo {
toString() {
return 'I am foo';
}
}
const foo = new Foo();
console.log(`${foo}`); // 'I am foo'
//Defined car Object
var car = {
type: "Fiat",
model: 500,
color: "white",
//.toString() Override
toString: function() {
return this.type;
}
};
//Various ways to test .toString() Override
console.log(car.toString());
console.log(car);
alert(car.toString());
alert(car);
//Defined carPlus Object
var carPlus = {
type: "Fiat",
model: 500,
color: "white",
//.toString() Override
toString: function() {
return 'type: ' + this.type + ', model: ' + this.model + ', color: ' + this.color;
}
};
//Various ways to test .toString() Override
console.log(carPlus.toString());
console.log(carPlus);
alert(carPlus.toString());
alert(carPlus);
只需重写toString()
方法即可。
简单示例:
var x = {foo: 1, bar: true, baz: 'quux'};
x.toString(); // returns "[object Object]"
x.toString = function () {
var s = [];
for (var k in this) {
if (this.hasOwnProperty(k)) s.push(k + ':' + this[k]);
}
return '{' + s.join() + '}';
};
x.toString(); // returns something more useful
如果您定义了一个新类型,它的表现会更好:
function X()
{
this.foo = 1;
this.bar = true;
this.baz = 'quux';
}
X.prototype.toString = /* same function as before */
new X().toString(); // returns "{foo:1,bar:true,baz:quux}"
v0.10.*
或 Chrome Version 32.0.1700.102
中不行。虽然直接调用 toString (笨拙) 或使用类型强制转换 (更糟) 可以解决这个问题,但是 console[/info|log/] 使用了旧版的未改良的 toString。 - james_womackFunction.prototype.named= function(ns){
var Rx= /function\s+([^(\s]+)\s*\(/, tem= this.toString().match(Rx) || "";
if(tem) return tem[1];
return 'unnamed constructor'
}
function whatsit(what){
if(what===undefined)return 'undefined';
if(what=== null) return 'null object';
if(what== window) return 'Window object';
if(what.nodeName){
return 'html '+what.nodeName;
}
try{
if(typeof what== 'object'){
return what.constructor.named();
}
}
catch(er){
return 'Error reading Object constructor';
}
var w=typeof what;
return w.charAt(0).toUpperCase()+w.substring(1);
}
这里是一个将 Map 对象转换为字符串的示例:
Map.prototype.toString = function() {
let result = {};
this.forEach((key, value) => { result[key] = value;});
return JSON.stringify(result);
};
typeof
更好)。 - alex