我对我的syllables做完全相同的事情时,似乎无法遍历我的word。然而这行得通,怎么来?

我的JSON:

{
  "main_object": {
    "id": "new",
    "getExerciseTitle": "Example",
    "language": "nl_NL",
    "application": "lettergrepen",
  "main_object": {
    "title": "Example",
    "language": "nl_NL",
    "exercises": [{
      "word": "espresso",
      "syllables": [
        "es",
        "presso",
        "",
        ""
      ]
    }]
  },
  "dataType": "json"
}


}

我的syllables循环:

var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exerSyll, s) {
  $(".syllable" + s).val(exercise.syllables)
});


我的word循环确实起作用:

var exercise = json.main_object.main_object.exercises;
$.map(exercise, function(exercise, i) {
  $("#addOpdracht").click();
  $(".exerciseGetWordInput_" + i).val(exercise.word)
});


应该在其后附加syllables的位置:

function getWordPartInput(id, cValue){
  cValue = cValue || '';
  var wpInput = $('<input/>', {
    'class': 'form-group form-control syllable',
    'type': 'text',
    'value': cValue,
    'placeholder': 'Syllables',
    'name': 'Syllablescounter['+ SyllablesID++ +']'
   });
  return wpInput;
}


是否可以创建一个循环并将syllables附加在音节输入中,并将word附加在练习输入中?还是必须是单独的循环?当我将其取回CMS时,我希望使用正确的syllables保留所需的word

需要澄清的图片:javascript - 我无法遍历JSON并获取数据-LMLPHP我正在尝试使音节带有所需的单词。

最佳答案

您的问题是您在exerSyll函数回调中使用了map,因此它会悬挂原始声明的exerSyll变量,这就是为什么在代码中得到Ecxeption的原因:

//First declaration of exerSyll
var exerSyll = json.main_object.main_object.exercises;

//Reusing the same variable exerSyll in the callback
$.map(exerSyll, function(exerSyll, s) {
  //Will cause an exception beacause exerSyll declaration will be hoisted
  $(".syllable" + s).val(exercise.syllables)
});


您应该在回调中对变量使用另一个名称,以避免发生Exception。

var exerSyll = json.main_object.main_object.exercises;

$.map(exerSyll, function(exer, s) {
  console.log(exer.syllables)
});


演示:

这是一个有效的演示,显示了问题的解决方案。



var json = {
  "main_object": {
    "id": "new",
    "getExerciseTitle": "Example",
    "language": "nl_NL",
    "application": "lettergrepen",
    "main_object": {
      "title": "Example",
      "language": "nl_NL",
      "exercises": [{
        "word": "espresso",
        "syllables": [
          "es",
          "presso",
          "",
          ""
        ]
      }]
    },
    "dataType": "json"
  }
};

var exerSyll = json.main_object.main_object.exercises;

$.map(exerSyll, function(exer, s) {
  console.log(exer.syllables)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

10-05 22:24