首页 > 解决方案 > Why do i get Undefined when i try to populate this literal template?

问题描述

I set a local storage item, an array to be more accurate.

Then I get it and try to populate my literal template but I get an undefined

undefined:1 GET http://localhost/undefined 404 (Not Found) on undefined:1

Here's my code:

var rawRelatedProductCategoryArray = localStorage.getItem('relatedCategoryProductsSelected');

var parsedRelatedProductArray = ('rawRelatedProductCategoryArray', JSON.parse(rawRelatedProductCategoryArray));

console.log(parsedRelatedProductArray); // on this i get the result of my array

document.getElementById("relatedProducts").innerHTML = `${parsedRelatedProductArray.map(relatedProductsTemplate).join('')}`

Here's the template i'm trying to put the array data in it:

function relatedProductsTemplate(relatedProduct) {
  return `
   <div class="relatedDiv">
    <div class="item mb-0 text-center ">
      <div>
        <div class="post-prev-img">
          <a href="#"><img src="${relatedProduct.image}" alt="img"></a>
        </div>
        <div class="post-prev-title mb-5">
          <h3><a class="font-norm a-inv" href="shop-single.html">${relatedProduct.dataProduct}</a></h3>
        </div>
        <div class="shop-price-cont">
          <strong>${relatedProduct.price}</strong>
        </div>
      </div>
    </div>
  </div>
  `
}

标签: javascriptarrayslocal-storageliterals

解决方案


我发现我做错了什么:

问题是因为数组是嵌套的。

所以我确实喜欢这样:

  var arrayNesting = parsedRelatedProductArray[0];

然后我将 var 传递给这样的文字:

  document.getElementById("relatedProducts").innerHTML =
    `${arrayNesting.map(relatedProductsTemplate).join('')}`

推荐阅读