2017-04-21 65 views
1

我試圖獲取一個數組對象並更改它的打印表示 - 只是該對象,而不是程序中的所有數組。我希望設置的toString屬性將做的工作,但它並不:忽略JavaScript數組的打印表示

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)

我缺少什麼?

+2

'console.log()'代碼做它想做的事情。當數組被強制爲字符串值時,覆蓋'.toString()'將起作用,但除非強制執行,否則'console.log()'不一定會這樣做。 – Pointy

+0

Duplicate http://stackoverflow.com/questions/9943257/how-do-i-override-the-default-output-of-an-object – mplungjan

+0

檢查鏈接[鏈接](http://stackoverflow.com/問題/ 6307514/is-it-it-it-it-over-javascript-tostring-function-to-provide-meaningfu),你可以看到如何做到這一點; –

回答

0
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);