JSON Parse for和while循环的多级数组导致未定义

时间:2019-06-04 20:05:30

标签: javascript json jsonparser

我的脚本遍历了不同的对象,但是从图像数组的“ for”循环中收到未定义的结果。

可以在此处查看JSON数据:https://michaelpmullally.com/map/map.json

我尝试使用不同类型的循环,并尝试为数组中的每个项目创建单独的变量。

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    console.log(myObj);
    for (i = 0; i < myObj.features.length; i++) {
        for (h = 0; h < myObj.features[i].image.length; h++) {
            var name = myObj.features[i].properties.name;
            var image = myObj.features[i].image[h]; //updated from answers !! JSON also updated
            while (h < 5) {
                var slidelink = `<a href="#` + name + `-slide-` + h + `">` + h + `</a>`;
                var slideimage = `<div class="slides">
                    <picture class="slide" id="` + name + `-slide-` + h + `">` + h + `">
                        <img src="` + image + `">
                    </picture>
                </div>`;
            }
            var slider = slidelink + slideimage;
        }
        var name = myObj.features[i].properties.name;
        var icon = myObj.features[i].properties.icon;
        var yelp = myObj.features[i].properties.yelp;
        var trip = myObj.features[i].properties.trip;
        var rating = myObj.features[i].properties.rating;
        var review = myObj.features[i].properties.content;
        document.getElementById("locations"+ i).innerHTML = `<header>
        <h2><i class="` + icon + `"></i> ` + name + `</h2>
        </header>
        <main>
            <section class="slider">`
                + slider +
           `</section> 
            <section class="review">
                <span>` + rating + `</span>
                ` + review + `
            </section>
        </main>
        <footer>
        <h2><a href="https://www.yelp.com/biz` + yelp + `"><i class="fab fa-yelp"></i></a>
        <a href="https://www.tripadvisor.com/` + trip + `"><i class="fab fa-tripadvisor"></i></a></h2>
        </footer>
        `;
    }
}
};
xmlhttp.open("GET", "map.json", true);
xmlhttp.send();

顶部文章块应该是它的外观。 https://michaelpmullally.com/map/test.html

2 个答案:

答案 0 :(得分:0)

简单错误

for (h = 0; h < myObj.features[i].image.length; h++) {  <-- looping over images
  var name = myObj.features[i].properties.name;
  var image = myObj.features[i].image.file[h];  <-- using index on file[h], not image[h]

答案 1 :(得分:0)

我假设您可能想使用files数组中描述的images之一,如果可以的话

// the index value h is on the image and not on the file
var image = myObj.features[i].image[h].file[0];  // you have misplaced your index `h`, also am simply placing the index 0 here for reference.

也不确定在图像下处理不同文件的方式和位置,如果需要,还需要遍历files array