简体   繁体   English

Json Array在第二个for循环中未定义

[英]Json Array is undefined in the second for loop

I have a Json with urls to pictures and a corresponding number. 我有一个Json,带有指向图片的网址和相应的编号。 I am running it through two for loops, which works fine in the first one, but not in the second. 我正在通过两个for循环来运行它,在第一个循环中工作正常,但在第二个中则无法。 Can you tell me why it shows me 'undefined' in the second one? 您能告诉我为什么在第二篇文章中显示为“未定义”吗?

   {
    "sources": [
        {"pic": "../img/Bild1.png", "number": "1"},
        {"pic": "../img/Bild2.png", "number": "2"},

        {"pic": "../img/Bild9.png", "number": "9"},
        {"pic": "../img/Bild10.png","number": "10"}
]
}

 var url = "../js/Bildquelle.json"; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState === 4 && xhttp.status === 200) { var json = JSON.parse(xhttp.responseText); gameStart(json.sources); } }; xhttp.open("GET", url, true); //Resource beziehen, true= synchron xhttp.send(); //Anfrage abschicken function gameStart(Bildquelle) { // Create the pile of shuffled cards in random order Bildquelle.sort(function() { return Math.random() - .5 }); for (var i = 0; i < 10; i++) { var Karte = $('<img src=' + Bildquelle[i].pic + ' alt="Bild">').data('number', Bildquelle[i].number).attr('id', 'card' + Bildquelle[i].number).appendTo('#cardPile').draggable({ containment: '#content', stack: '#cardPile img', cursor: 'move', revert: true }) }; // Create the card slots var number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (var j = 1; j <= 10; j++) { var Kartenslot = $('<div></div>').data('number', j).appendTo('#cardSlots').css('background-image', 'url(' + Bildquelle[j].pic + ')').attr('id', 'slot' + number[j - 1]).droppable({ accept: '#cardPile img', hoverClass: 'hovered', drop: handleCardDrop }); } }; 

If es6 support available, use let i instead of var i or change var name in second for . 如果es6支持可用,请使用let i代替var ivar name in second for更改var name in second for

var create scope to function level. var创建scope

You are defining the variable i in both loops. 您正在两个循环中定义变量i Try to change the variable of the second loop for another one or trying using block scoping 尝试将第二个循环的变量更改为另一个循环,或尝试使用块作用域

    for (let i = 0; i < 10; i++) {
        /* i is defined here */ 
    }
    /* i is not defined here * /

This will give you the option to declare the variable i in both loops without errors. 这将使您可以选择在两个循环中声明变量i而不出错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM