2 回答

TA貢獻1864條經驗 獲得超6個贊
幾個問題
不存在,
類型不存在(它是類型,JS 區分大小寫)
hmtl += 對象不起作用
mcve 會像這樣有用:
const data = [
{ "Type":"Ford", "Model":"mustang" },
{ "Type":"Dodge", "Model":"ram" }
]
var text = [];
data.forEach(function(these) {
text.push(these.Type)
});
document.getElementById('special').textContent = text.join(", ");
<div id="special"></div>
更多詳情:
const data = [
{ "Type":"Ford", "Model":"mustang" },
{ "Type":"Dodge", "Model":"ram" }
]
var html = [];
data.forEach(function(these) {
html.push(`<li>${these.Type}: ${these.Model}</li>`)
});
document.getElementById('special').innerHTML = html.join("");
<ul id="special"></ul>

TA貢獻1812條經驗 獲得超5個贊
您正在將一個 JavaScript 對象附加到 html 字符串中,該字符串理論上將計算為 或類似的東西。如果您希望 s 顯示在 HTML 本身中,則只需將對象括在引號中,或調用 ,即可。其次,您嘗試將對象的鍵設置為對象本身的引用,但鍵本身(除非被 s 包圍)不會反映局部變量;而是文字字符串本身。"[object Object]"{}JSON.stringify(obj)[]
所以這里的“這些”是一個變量名稱,試圖在JSON鍵中引用,但作為一個鍵,它將評估為字符串文字“these”,以解決這些問題,將“這些”括在括號中,JSON.stringify整個事物,或者整個對象在s中并將變量值連接到它,所以要么:"
var html = '';
data.forEach(function (these) {
html += "{ " + these + ": " + res.type + "}"/*or some other string based on */;
});
或
var html = '';
data.forEach(function (these) {
html += JSON.stringify({ [these]: res.type })/*or some other string based on */;
});
添加回答
舉報