我正在尝试获取一个数组对象并更改其打印表示形式 - 仅更改该对象的打印表示形式,而不是程序中的所有数组。我希望设置 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)
我错过了什么?
最佳答案
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);
关于javascript - 覆盖 JavaScript 数组的打印表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43542580/