当我在 JavaScript 程序中console.log()
一个对象时,我只看到输出[object Object]
,这对于弄清楚它是什么对象(甚至是什么类型的对象(不是很有帮助。
在 C# 中,我习惯于重写ToString()
以便能够自定义对象的调试器表示形式。我可以在 JavaScript 中做类似的事情吗?
在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
:
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 }
虽然没有检查的版本打印:
{ x: 1, y: 2 }
<小时 />更多信息(+ 在 class
es 中使用的示例(:
https://nodejs.org/api/util.html#util_util_inspect_custom
将"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和Promise(定义了内置的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'
在浏览器 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'
如果对象是由你自己定义的,你总是可以添加一个toString覆盖。
//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}"
你可以给任何自定义对象提供自己的toString方法,或者编写一个通用的方法来调用你正在查看的对象-
Function.prototype.named= function(ns){
var Rx= /functions+([^(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);
}
- 此操作需要大量时间 完整,根据Mozilla文档,不鼓励使用它:https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/proto
-显然,现代浏览器已弃用.prototype,ECMA6指定 请改用proper__proto__。
因此,例如,如果您要定义自己的对象地理位置,则应调用__proto__属性而不是 .prototype:
var geoposition = {
lat: window.pos.lat,
lng: window.pos.lng
};
geoposition.__proto__.toString = function(){ return "lat: "+this.lat+", lng: "+this.lng }
console.log("Searching nearby donations to: "+geoposition.toString());
下面是一个如何字符串化 Map 对象的示例:
Map.prototype.toString = function() {
let result = {};
this.forEach((key, value) => { result[key] = value;});
return JSON.stringify(result);
};
你不能!
在 2023 年,Chrome 不会将其控制台输出基于您可以控制的任何内容。
你能做的最好的事情就是把它输出到控制台.log强制对象强制的行。
而不是覆盖toString()
,如果你包括原型JavaScript库,你可以使用Object.inspect()
来获得更有用的表示。
大多数流行的框架都包含类似的东西。
Chrome 控制台日志允许您检查对象。
您可以在 JS 中扩展或覆盖
String.prototype.toString = function() {
return this + "..."
}
document.write("Sergio".toString());
A simple format Date function using Javascript prototype, it can be used for your purpose
https://gist.github.com/cstipkovic/3983879 :
Date.prototype.formatDate = function (format) {
var date = this,
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds();
if (!format) {
format = "MM/dd/yyyy";
}
format = format.replace("MM", month.toString().replace(/^(d)$/, '0$1'));
if (format.indexOf("yyyy") > -1) {
format = format.replace("yyyy", year.toString());
} else if (format.indexOf("yy") > -1) {
format = format.replace("yy", year.toString().substr(2, 2));
}
format = format.replace("dd", day.toString().replace(/^(d)$/, '0$1'));
if (format.indexOf("t") > -1) {
if (hours > 11) {
format = format.replace("t", "pm");
} else {
format = format.replace("t", "am");
}
}
if (format.indexOf("HH") > -1) {
format = format.replace("HH", hours.toString().replace(/^(d)$/, '0$1'));
}
if (format.indexOf("hh") > -1) {
if (hours > 12) {
hours -= 12;
}
if (hours === 0) {
hours = 12;
}
format = format.replace("hh", hours.toString().replace(/^(d)$/, '0$1'));
}
if (format.indexOf("mm") > -1) {
format = format.replace("mm", minutes.toString().replace(/^(d)$/, '0$1'));
}
if (format.indexOf("ss") > -1) {
format = format.replace("ss", seconds.toString().replace(/^(d)$/, '0$1'));
}
return format;
};