2016-11-15 56 views
1

嘿,我在JS中有一個構造函數對象,並且希望看到所有對象,爲什麼會像這裏彈出[object Object]? MyCodeFiddle對象顯示對象的對象問題

+1

'JSON.stringify(pers);' –

+0

Beacuse'var pers = new Person(「John」,「Colin」,47,「blue」);''是不能直接附加對象的對象。你必須把它串聯起來。 (document.getElementById(「data」)。innerHTML = JSON.stringify(pers);' –

回答

0

您可以通過遍歷所有的對象鍵和填充新創建persArr與對象pers屬性的值。

最後只有一個電話,你可以得到所有以逗號persArr.join(', ')適當分隔的屬性值:

function Person(first, last, age, eyecolor) { 
 
    this.first = first; 
 
    this.last = last; 
 
    this.age = age; 
 
    this.eyecolor = eyecolor; 
 
} 
 

 
var pers = new Person('John', 'Colin', 47, 'blue'), 
 
    persArr = []; 
 

 
Object.keys(pers).forEach(function(key) { 
 
    persArr.push(pers[key]); 
 
}); 
 

 
document.getElementById('data').innerHTML = persArr.join(', ');
#data { 
 
    display: flex; 
 
    width: 120px; 
 
    height: 40px; 
 
    border: 1px solid #000; 
 
    background-color: #fff; 
 
    justify-content: center; 
 
    align-items: center; 
 
}
<div id="data"></div>

更妙的是,你可以創建你的人物原型的新方法,妥善得到您要的信息:

function Person(first, last, age, eyecolor) { 
 
    this.first = first; 
 
    this.last = last; 
 
    this.age = age; 
 
    this.eyecolor = eyecolor; 
 
} 
 

 
Person.prototype.getInfo = function() { 
 
    return `${this.first} ${this.last}, ${this.age} years old and ${this.eyecolor} eyes.`; 
 
} 
 

 
var pers = new Person('John', 'Colin', 47, 'blue'); 
 
document.getElementById('person').innerHTML = pers.getInfo();
<div id="person"></div>

如果你想打印物體調試目的:

  • 輸出控制檯:

    console.log(pers);

  • 輸出作爲一個字符串,在HTML中,通過使用JSON.stringify()

    document.getElementById('data').innerHTML = JSON.stringify(pers, null, 4);

0

直接給予時HTML代碼中顯示[對象對象]將顯示爲這些對象是默認行爲

如果你真的想顯示HTML有兩種方式

1)迭代字符串化的對象JSON

0對象屬性

for(var i in pers) { 
    document.getElementById("data").innerHTML = document.getElementById("data").innerHTML + pers[i] + ','; 
} 

http://jsfiddle.net/upwLvhs5/2/

2)

document.getElementById("data").innerHTML = JSON.stringify(pers) 

http://jsfiddle.net/upwLvhs5/3/