首页 > 解决方案 > json对象中的for循环

问题描述

我想在下面的 json 数据中循环。console.log 可以正常工作,但不能在 javascript 函数中工作。我希望 for for 循环在 javascript 函数中工作。我希望javascript函数中的结果像

<script>
(function() {
      var questions = [ {
      question: "What is the value of 2 * 4";
      choices :[4, 8, 99, 11];
      correctAnswer: 1;},
{
      question: "What is the value of 2 * 8";
      choices :[4, 8, 16, 11];
      correctAnswer: 2;},

      ];

</script>

但是在控制台中出现错误。控制台错误“预期的表达式,得到关键字'for'”这些是我的代码

<?php
$json_codes = array();


$sql = "SELECT  id, instructions,  quiz_question, correct, wrong, wrong1, wrong2  FROM student_quiz WHERE  subject ='SOCIAL STUDIES' AND type = 'challenge' ";
$results = $pdo->query($sql);
$results->setFetchMode(PDO::FETCH_ASSOC);
while($row = $results->fetch()) {
    $json_array['instructions'] = $row['instructions'];
    $json_array['quiz_question'] = $row['quiz_question'];
    $json_array['correct'] = $row['correct'];
    $json_array['wrong'] = $row['wrong'];
    $json_array['wrong1'] = $row['wrong1'];
    $json_array['wrong2'] = $row['wrong2'];
    array_push($json_codes,$json_array);
}

echo json_encode($json_codes);

?>
<script>
         var obj = <?php echo json_encode($json_codes);?>;

(function() {
  var questions = [ 

  for(a=0; a<obj.length; a++){
         document.write(obj[a]);

         }

  ];

标签: javascriptphpmysqljson

解决方案


您确实尝试在数组的定义范围内表达循环。这是一个语法错误。

我建议使用for ( var something in obj )for ( var something of obj )不使用增量驱动的for循环。根据您想要执行的操作,这可能首先会对循环性能产生影响,并且至少这些-loops 比orfor更难阅读(和维护)。for ( ... in ... )for ( ... of ... )

您应该了解 JavaScript 语法的工作原理。数组的定义仅限于关联,您不能将处理指令(如循环)放在数组定义中(扩展运算符除外)。当使用循环将更多数据迁移到数组/对象时,您必须在定义之后运行它们。

至少,您应该考虑不要将定义放在(function() { ... })();指令之外,这些指令可能不受use strict-directives 或该指令遵循的惰性执行模型和范围排除的影响。


推荐阅读