Looping through a JSON Array gives "undefined" results

This question already has an answer here:

  • Why is using “for…in” with array iteration a bad idea? 25 answers
  • JavaScript for…in vs for 23 answers

  • 你忘记访问AlmostThere

      jsonData.TheArray[i].AlmostThere.whatWeAreLookingFor
    

    for (var i = 0; i < jsonData.TheArray.length; i++) {
        console.log(jsonData.TheArray[i].AlmostThere.whatWeAreLookingFor);
    }
    

    If you loop your array TheArray in your way, the contents var will become these two objects:

    {  
         "AlmostThere": {  
            "whatWeAreLookingFor":"Hello"
         }
    }
    

    and

    {
        "AlmostThere": {
            "whatWeAreLookingFor":"Goodbye"
        }
    }
    

    Now you want to access the value with

    contents.whatWeAreLookingFor

    but this attribute is undefined for these objects. So your console logs undefined . You have to access the value with that:

    contents.AlmostThere.whatWeAreLookingFor
    

    So you get the object AlmostThere and select the attribute whatWeAreLookingFor .

    If your using jquery you should use:

    $.each(jsonData.TheArray, function() {
         console.log(contents.AlmostThere.whatWeAreLookingFor + '!');
    });
    

    API: http://api.jquery.com/jquery.each/


    for... in iterates over the keys of an object. For an array, that means (approximately) the indexes 0 , 1 , 2 , etc.

    You could use Array.prototype.forEach instead:

    jsonData.theArray.forEach(function(contents) {
      console.log(contents.AlmostThere.whatWerAreLookingFor);
    })
    
    链接地址: http://www.djcxy.com/p/70018.html

    上一篇: JavaScript的

    下一篇: 通过JSON数组循环提供“未定义”结果