【问题标题】:Override print representation of a JavaScript array [duplicate]覆盖 JavaScript 数组的打印表示
【发布时间】:2017-09-18 10:46:06
【问题描述】:

我正在尝试获取一个数组对象并更改其打印表示 - 仅针对该对象,而不是程序中的所有数组。我希望设置 toString 属性可以完成这项工作,但它没有:

var a = [1, 2, 3]

// Prints using the default representation
console.log(a)

// Try to override toString
a.toString = function() {
  return 'some new representation'
}

// Still uses the default representation
console.log(a)

我错过了什么?

【问题讨论】:

  • console.log() 代码做它想做的事。当数组被强制为字符串值时,覆盖.toString() 将起作用,但console.log() 不一定会这样做,除非你强制它这样做。
  • 检查链接link,你可以看到如何正确地做到这一点;

标签: javascript arrays node.js


【解决方案1】:
var a = [1, 2, 3];

// Prints using the default representation
console.log(a);

// Try to override toString
a.toString = function() {
  return 'some new representation'
}

// append blank string to invoke toString function
console.log(""+a);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    相关资源
    最近更新 更多