在 getJSON returns undefined 中使用每个函数

Using the each function within getJSON returns undefined

我正在使用 jQuery 的 getJSON 方法来检索和解析一个简单的 JSON 文件,但是当我将值输出到我的页面时,它显示为 undefined

$.getJSON( 'js/example.json', function ( data ) {

    var output = '';

    $.each( data.exercises, function ( index, exercise ) {
        output += '<li>' + exercise.work.weight + ' x ' + exercise.work.reps  + '</li>';
    });

    $( '#example' ).html( output );

});

example.json

{

    "exercises" : [

        {
            "name" : "Squats",
            "work" : [
                {
                    "weight" : 135,
                    "reps" : 5
                },
                {
                    "weight" : 225,
                    "reps" : 5
                },
                {
                    "weight" : 315,
                    "reps" : 5
                }
            ]

        },
        {
            "name" : "Bench",
            "work" : [
                {
                    "weight" : 135,
                    "reps" : 5
                },
                {
                    "weight" : 225,
                    "reps" : 5
                },
                {
                    "weight" : 315,
                    "reps" : 5
                }
            ]

        },
        {
            "name" : "Rows",
            "work" : [
                {
                    "weight" : 135,
                    "reps" : 5
                },
                {
                    "weight" : 225,
                    "reps" : 5
                },
                {
                    "weight" : 315,
                    "reps" : 5
                }
            ]

        }

    ]


}

我认为错误可能出在我的每个函数中,但我还没有能够识别它。有什么想法吗?

这个:

output += '<li>' + exercise.work.weight + ' x ' + exercise.work.reps  + '</li>';

假设您的 JSON 看起来像:

"exercises" : [
  {
    "name" : "Squats",
    "work" : 
      {
        "weight" : 135,
        "reps" : 5
      }
  },

实际上 work 在每种情况下都是一个数组。

你想要这样的东西:

$.each( data.exercises, function ( index, exercise ) {

   $.each( exercise.work, function( index, workout ) { 
      output += '<li>' + workout.weight + ' x ' + workout.reps  + '</li>';
   });

});

你的练习作品是一个数组,需要另一个循环

$.each( data.exercises, function ( index, exercise ) {
    $.each(exercise.work, function (index, work) {
         console.log(work);
    });
});