我不明白为什么我的for循环返回“未定义”

时间:2019-11-02 16:45:41

标签: javascript for-loop

我试图同时为两个数组创建一个循环,但是执行返回“ undefined”,但我不明白为什么...请您看一下我的代码并向我展示办法 ?

var questions = ["a", "b", "c"];
var responses = [5, 45, "test"];

var correctionList = "";
for (var i = 0; i < questions.length; i++); {

  correctionList += questions[i] + ' : ' + responses[i];

  var newLi = document.createElement('li');
  var liContent = document.createTextNode(correctionList);
  newLi.appendChild(liContent);

  console.log(correctionList);

  var showCorrection = document.querySelector('#correction-list');
  showCorrection.appendChild(newLi);

  console.log(liContent);
}
<ol id="correction-list"></ol>

我希望列表中包含“问题:答复”

1 个答案:

答案 0 :(得分:0)

您看到的最后一个undefined可能是由于缺少函数return语句。仅当您在浏览器控制台上打印某些内容时,这种情况才会发生。

只需重构一下代码即可以问题:响应格式显示问题列表和答案

function createList() {
    var questions = ["a", "b", "c"];
    var responses = [5, 45, "test"];

    for (var i = 0; i < questions.length; i++) {

       // Changed this line
       var correctionList = questions[i] + ' : ' + responses[i];

       var newLi = document.createElement('li');
       var liContent = document.createTextNode(correctionList);
       newLi.appendChild(liContent);

       var showCorrection = document.querySelector('#correction-list');
       showCorrection.appendChild(newLi);
}

createList();