微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么 JSON 数据在 JavaScript 中显示“未定义”?

如何解决为什么 JSON 数据在 JavaScript 中显示“未定义”?

嘿,我正在尝试使用我的 JSON 文件显示一些引号。但它显示未定义。任何人都可以检查以下 html 和 JavaScript。

我的 Javascript

const resultEl = document.querySelector('.allquotes');
const pageSize = document.querySelector('select[name="page-size"]');
const pageCurr = document.querySelector('input[name="page-curr"]')
const resultCount = document.querySelector('.result-count')
const pageNoCurr = document.querySelector('.page-no-curr');
const pageNoCount = document.querySelector('.page-no-count')
const btnFirst = document.querySelector('.page-btn-first');
const btnPrev = document.querySelector('.page-btn-prev');
const btnNext = document.querySelector('.page-btn-next');
const btnLast = document.querySelector('.page-btn-last');

let results = [];

const getResultCount = () => results.length;
const getPageSize = () => +pageSize.value;
const getCurrPage = () => +pageCurr.value;
const getPageCount = () => Math.ceil(getResultCount() / getPageSize());

const pageResponse = (records,pageSize,page) =>
  (start => records.slice(start,Math.min(records.length,start + pageSize)))
  (pageSize * (page - 1));

const main = async() => {
  btnFirst.addEventListener('click',navFirst);
  btnPrev.addEventListener('click',navPrev);
  btnNext.addEventListener('click',navNext);
  btnLast.addEventListener('click',navLast);
  pageSize.addEventListener('change',changeCount);

  results = await retrieveAllQuotes();
  updatePager(results);
  redraw();
};
const redraw = () => {
  resultEl.innerHTML = '';
  const paged = pageResponse(results,getPageSize(),getCurrPage());
  const contents = document.createElement('div');
  contents.innerHTML = paged.map(record => `<div class='latestatus'><p class='copytxt'>${record.quotes}</p><div> <button class="copystatus btn">copy</button></div></div>`).join('');
  resultEl.append(contents);
};

const navFirst = (e) => {
  pageNoCurr.textContent = 1;
  pageCurr.value = 1;
  redraw();
}

const navPrev = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const prevPage = curr > 1 ? curr - 1 : curr;
  pageCurr.value = prevPage;
  pageNoCurr.textContent = prevPage;
  redraw();
}

const navNext = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const nextPage = curr < pages ? curr + 1 : curr;
  pageCurr.value = nextPage;
  pageNoCurr.textContent = nextPage;
  redraw();
}

const navLast = (e) => {
  pageNoCurr.textContent = getPageCount();
  pageCurr.value = getPageCount();
  redraw();
}

const changeCount = () => {
  updatePager();
  redraw();
};

const updatePager = () => {
  const count = getPageCount();
  const curr = getCurrPage();
  pageCurr.value = curr > count ? 1 : curr;
  pageNoCurr.textContent = curr > count ? 1 : curr;
  pageNoCount.textContent = count;
  resultCount.textContent = getResultCount();
};

const retrieveAllQuotes = async function() {
  // here we are making a network call to your api
  const response = await fetch('/stat.json');
  
  // then converting it to json instead of a readable stream
  const data = await response.json();

  // finally go over the array and return new object with renamed key
  const results = data.map(val => ({quotes: val.status}));

  return results;
}

main();

我的 HTML

<div class="allquotes"></div>
<div class="pagable-status">
  <label>Page <span class="page-no-curr">1</span> of <span class="page-no-count">1</span></label>
  <div class="pagable-actions">
    <button class="page-btn-first">&#x226A;</button>
    <button class="page-btn-prev">&#60;</button>
    <input type="number" name="page-curr" min="1" value="1" />
    <button class="page-btn-next">&#62;</button>
    <button class="page-btn-last">&#x226B;</button>
    <select name="page-size">
      <option>5</option>
      <option>10</option>
      <option>20</option>
    </select>
  </div>
  <label>(<span class="result-count"></span> items)</label>
</div>

我说我使用的是 JSON 文件。您可以在 javascript 上注意到它。有一个名为 stat.json文件名。 在我的 javascript 中的位置

const retrieveAllQuotes = async function() {
  // here we are making a network call to your api
  const response = await fetch('/stat.json');

stat.json 的内容

[
    {
        "quotes":"Do what is right not what is easy."
    },{
        "quotes":"hey there,Whatsapp is using me."
    },{
        "quotes":"Too Busy"
    },{
        "quotes":"Only you can give me that feeling."
    },{
        "quotes":"I had a horribly busy day in converting oxygen into carbon dioxide"
    },{
        "quotes":"Be yourself; everyone else is already taken"
    },{
        "quotes":"Your attitude may hurt me,But main can Kill You!!"
    },{
        "quotes":"love is Blind,be careful."
    },{
        "quotes":"'SUCCESS' is depend on U."
    },{
        "quotes":"If you love someone set it free."
    },{
        "quotes":"love is sweet,When it's new. But it is sweeter when it's true."
    },{
        "quotes":"Where ther is love,there is life."
    },{
        "quotes":"Not always 'Available' try your luck.."
    },{
        "quotes":"I am not changed it's just I grew up and you should try too."
    },{
        "quotes":"The biggest slap to your enimies is your success."
    },{
        "quotes":"Born to express,not to impress."
    },{
        "quotes":"When nothing goes right! go left."
    },{
        "quotes":"I allow myself to be badass confident in all that I do."
    },{
        "quotes":"Sometimes you succeed and other time you learn."
    },{
        "quotes":"A true friend sees the first tear,catches the second and stops the third."
    },{
        "quotes":"We carry our childhood with us!!"
    },{
        "quotes":"Childhood is the most beautiful of all lige's season!!"
    }
]

而这些引号要显示在由 Javascript 创建的 <p class="copytxt"> 元素中。在我的 javascript 中的位置

  contents.innerHTML = paged.map(record => `<div class='latestatus'><p class='copytxt'>${record.quotes}</p><div> <button class="copystatus btn">copy</button></div></div>`).join('');
  resultEl.append(contents);
};

如果我运行此代码,它会显示所有未定义的引号。请如果有人有时间运行上面的代码并测试两次。

解决方法

删除这部分

  // finally go over the array and return new object with renamed key
  const results = data.map(val => ({quotes: val.status}));

  return results;

并返回data,您的json中不存在字段status,并且为了具有相同的架构而重新映射json是完全没用的。

,

我终于得到了答案。这是映射错误。这是@Barmar 的回答

const results = data.map(val => ({quotes: val.quotes}));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。