亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的函數不返回我想要的 JSON 數組項?

為什么我的函數不返回我想要的 JSON 數組項?

尚方寶劍之說 2022-08-27 09:39:34
我有一個函數,我試圖將json文件的一些內容放入元素中。我從后端的函數接收此數組。我的函數打印出相同數量的對象,但不會打印出我嘗試抓取的特定項目??刂婆_日志打印出陣列剛剛好,所以我知道該部分正在工作。JSON 數組示例 [    { "Type":"Ford", "Model":"mustang" },    { "Type":"Dodge", "Model":"ram" }  ]斷續器<p id="special"></p>斷續器myMethod: function () {            var res = this;            fetch('/cont/function', {                method: 'POST',                headers: { 'Content-Type': 'application/json' }            })                .then(function (response) {                    return response.json();                })                .then(function (data) {                    res.type = data.Type;                    console.log(data);                    var html = '';                    data.forEach(function (these) {                        html += { these: res.type };                    });                    document.getElementById('special').innerHTML = html;                });        }
查看完整描述

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>


查看完整回答
反對 回復 2022-08-27
?
慕雪6442864

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 */;

});


查看完整回答
反對 回復 2022-08-27
  • 2 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號