如何获取我的音节,以便我可以对它们进行控制台记录

时间:2018-07-02 11:51:57

标签: javascript jquery

JSON如下所示:

{
"main_object": {
"id": "new",
"getExerciseTitle": "TestAfterCodeCleaning",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
  "title": "TestAfterCodeCleaning",
  "language": "nl_NL",
  "exercises": [
    {
      "word": "testikels",
      "syllables": [
        "test",
        "ikels",
        "",
        ""
      ]
    }
  ]
},
"dataType": "json"
 }
}

这是我尝试获取syllables的方式,以便我可以console.log()进行操作:

var jsyl = json.main_object.main_object.exercises.syllables;
但是,

问题是:这在我的console.log()中显示为未定义。为什么以及如何?

完整的代码如下:

function prepareCheck() {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
  $(document).on('keyup', '.syl-input', function() {
    var syllableval = $(idsyll).val();
     var jsyl = json.main_object.main_object.exercises.syllables;
  });
});
}

注意:JSON有一个syllables,因为我认为这对您来说更容易阅读,但是应该采取什么措施来获取所有syllables(如果有多个数组,则应该这样做) syllables)。

1 个答案:

答案 0 :(得分:0)

使用exercises[0]代替exercises,因为exercises是对象的数组,在这种情况下,索引为0处只有一项。

var jsyl = json.main_object.main_object.exercises[0].syllables;

var json = {
"main_object": {
"id": "new",
"getExerciseTitle": "TestAfterCodeCleaning",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
  "title": "TestAfterCodeCleaning",
  "language": "nl_NL",
  "exercises": [
    {
      "word": "testikels",
      "syllables": [
        "test",
        "ikels",
        "",
        ""
      ]
    }
  ]
},
"dataType": "json"
 }
}

var jsyl = json.main_object.main_object.exercises[0].syllables;

console.log(jsyl); // [ 'test', 'ikels', '', '' ]