【问题标题】:how do i access each item of an array stored in local storage individually?如何单独访问存储在本地存储中的数组的每个项目?
【发布时间】:2022-02-07 17:04:42
【问题描述】:

下面的代码从食物 api 中获取图像及其名称。一旦用户点击喜欢按钮,我就可以将这些图像存储在本地存储中。但是我想取回存储的图像和名称数据并将它们显示在收藏选项卡中。但我似乎无法做到这一点..有什么帮助吗?

        let myFavMeals=[]
   function getRandomMeal(){
 fetch('https://api.spoonacular.com/recipes/random? 
  number=10&apiKey=b354ffb530c5444da1eec4b02a3146be').then((data)=>{
  console.log(data)
  return data.json()
   }).then((completedata)=>{
 console.log(completedata.recipes)
  let data1=""
  completedata.recipes.forEach((recipe) => {
    const {
      id,
      title,
      readyInMinutes,
      extendedIngredients,
      servings,
      image,
      dishTypes,
      instructions,
    } = recipe;
      data1+=`  
      <div class="meal-header">
          <img src=${recipe.image} alt=${recipe.title} >
      </div>
      <div class="meal-body">
          <h6>${recipe.title}</h6>
          <p class="show">see recipes</p>
          <button class="fav-btn">
              <i class="fa fa-heart"></i>
          </button>
      </div>
      <div class="holder">
      <div class="meal-desc">
      <p>ready in : ${recipe.readyInMinutes} minutes</p>
      <center><h6>instructions</h6></center>
      <p>${recipe.instructions}  </p>
      </div>
      </div>`      
    })
    const meal=document.querySelector(".meal")
    meal.innerHTML=data1
   const holder=document.querySelector(".holder")
const show=document.querySelectorAll(".show")
show.forEach(shows=>{
    showcounter=0
    shows.addEventListener("click",()=>{
      holder.style.display="block"
      showcounter++
      if(showcounter== 2) {
      holder.style.display="none"
      }
    })
  })
const favBtns=meal.querySelectorAll(".fav-btn i")
const images = document.querySelectorAll('.meal-header > img')
favBtns.forEach((favBtn,i)=>{
  favBtn.addEventListener("click", ()=>{
    favBtn.classList.add("active")
    console.log(images[i].src, images[i].alt)     
    myFavMeals.push(images[i].src, images[i].alt)
    localStorage.setItem("myFavMeals", JSON.stringify(myFavMeals))
    showMeal()
})
})
      
 }).catch((err)=>{
  console.log(err)
    })
}
getRandomMeal()
    function showMeal(){
      let favmeal= JSON.parse(localStorage.getItem("myFavMeals"))
      favmeal.forEach(favmeals=>{
        let meallist=""   
        meallist+=`<ul>
             <li><img src=${favmeal} alt=${favmeal[i].alt}><span>${favmeal[i].alt}</span></li>
         </ul>`
       
         document.querySelector(".fav-meals").innerHTML+=meallist
      })
       

      }

【问题讨论】:

  • 请显示minimal reproducible example,这将大大提高获得帮助的机会。但无论如何,既然您正在执行 stringify,请在检索和访问它时解析它,就像普通的 JSON 对象一样......
  • 您正在存储这样的数组:[image_url, alt_text, image_url, alt_text, ...],但是当您从本地存储中获取它时,您对它的迭代与此结构完全不匹配。如果您想保留此数组结构,您需要使用步长为 2 的普通 for 循环进行迭代。但最好存储一个对象数组:[{image_url, alt_text}, {image_url, alt_text}...]
  • 另外,虽然您需要一个可重现的示例,但请勿使用 API 密钥发布代码——它们是您的私钥,甚至可能已付费,因此您不希望它们被公开。
  • @tromgy 指出。但是你能用一个代码示例来证明这一点吗?

标签: javascript arrays local-storage


【解决方案1】:

您可以使用对象文字将数组中的收藏夹保存为对象:

myFavMeals.push({src: images[i].src, alt: images[i].alt})

然后使用 srcalt 键在循环中访问它们:

function showMeal() {
  let favmeal = JSON.parse(localStorage.getItem("myFavMeals"));
  favmeal.forEach(favmeal => {
    let meallist = "";
    meallist += `<ul>
             <li><img src=${favmeal.src} alt=${favmeal.alt}><span>${favmeal.alt}</span></li>
         </ul>`;

    document.querySelector(".fav-meals").innerHTML += meallist;
  });
}

【讨论】:

  • 按预期工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 2021-09-02
相关资源
最近更新 更多