array console.log没有使用自定义类toString

时间:2016-11-12 16:38:59

标签: javascript tostring

Chrome 54.0.2840.71(64位)

我有一个从自定义类构建的对象数组。如果我console.log数组,如何让数组中的对象使用他们的toString函数而不必手动循环数组?这可能吗?

代码 jsfiddle

function MyClass(value) {
  MyClass.prototype.getValue = function() {
    return value;
  }
}
MyClass.prototype.toString = function() {
    return "[MyClass: " + this.getValue() + "]";
}

var mc0 = new MyClass(0);
var mc1 = new MyClass(1);
console.log([mc0, mc1]);

当前输出

[MyClass, MyClass]

所需输出

[[MyClass: 0], [MyClass: 1]]

1 个答案:

答案 0 :(得分:0)

console.log不显示对象的字符串表示形式,而是显示表示其JSON表示法的树。如果你想要字符串表示,无论如何,传递一个字符串。

function MyClass(value) {
  this.getValue = function() { // As a side note, don't overwrite the prototype in constructor
    return value;
  }
}
MyClass.prototype.toString = function() {
    return "[MyClass: " + this.getValue() + "]";
}

var mc0 = new MyClass(0);
var mc1 = new MyClass(1);
console.log([mc0, mc1].toString());
// OR
console.log("%s",[mc0, mc1]);

此外,这不是console.log唯一的事情。它还对某些对象(如DOM元素)进行特殊处理。有关详细信息,请参阅MDN page