You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展中数组可在console正常打印 无法正确显示到HTML DOM

问题原因

直接把包含对象的数组传给.text()方法时,JavaScript会自动调用对象的默认toString()方法,普通对象的toString()返回值就是[object Object],所以才会出现你看到的结果。console.log是开发者工具专门做了优化,可以直接解析展示对象的内部结构,和DOM插入的逻辑不一样。


解决方法

方法1:输出格式化JSON字符串

JSON.stringify可以直接解决你的问题,它能把JS对象/数组序列化成可读的JSON字符串,还可以加参数实现缩进格式化,修改输出部分的代码即可:

chrome.storage.local.get({wsitemadded: []}, function (result) {
  var wsitemadded = result.wsitemadded;
  console.log(wsitemadded);
  // 三个参数分别为:要序列化的对象、替换函数(不需要填null)、缩进空格数
  $('#anydiv').text(JSON.stringify(wsitemadded, null, 2));
});

如果需要更清晰的排版,可以配合<pre>标签输出:

$('#anydiv').html(`<pre>${JSON.stringify(wsitemadded, null, 2)}</pre>`);

方法2:渲染为结构化HTML(更适合用户查看)

如果你不想输出 raw JSON,而是要渲染成正常的页面内容,可以遍历数组拼接HTML:

chrome.storage.local.get({wsitemadded: []}, function (result) {
  const wsitemadded = result.wsitemadded;
  let htmlStr = '';
  // 遍历数组里的每个商品对象
  wsitemadded.forEach(item => {
    htmlStr += `
    <div class="ws-item">
      <img src="${item.WSImage}" alt="${item.WSTitle}" style="width:100px">
      <h3>${item.WSTitle}</h3>
      <p>商品编号:${item.WSItemNumber}</p>
      <p>现价:${item.WSPrice}</p>
      <p>原价:${item.WSPrevPrice}</p>
      <p>配送日期:${item.WSDELDate}</p>
    </div>
    `
  })
  $('#anydiv').html(htmlStr);
});

额外优化建议

你现在用setTimeout等待存储写入完成的逻辑不稳定,最好把读取逻辑放到chrome.storage.local.set的回调里,避免因为存储写入耗时波动导致读取到旧数据:

chrome.storage.local.get({wsitemadded: []}, function (result) {
  var wsitemadded = result.wsitemadded;
  // 省略收集数据、push到数组的代码
  chrome.storage.local.set({ wsitemadded: wsitemadded }, function(){
    // 存储写入完成后直接读取,不需要定时器
    chrome.storage.local.get({wsitemadded: []}, function (readResult) {
      // 此处写渲染逻辑
    })
  });
});

内容的提问来源于stack exchange,提问作者aussiedan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 02:18:03