我的Javascript循环中出现“未定义”

时间:2018-04-02 12:25:36

标签: javascript arrays javascript-objects

我有这样的代码:

var students = [
          {
            name: 'Mustafa',
            track: 'A',
            achievements: 5,
            points: 500
          },
          {
            name: 'Ersin',
            track: 'B',
            achievements: 6,
            points: 600
          },
          {
            name: 'Ahmet',
            track: 'C',
            achievements: 7,
            points: 700
          },
          {
            name: 'Mehmet',
            track: 'D',
            achievements: 8,
            points: 800
          },
          {
            name: 'Cafer',
            track: 'E',
            achievements: 9,
            points: 900
          }
        ];
        
        var HTML;
        var s = 0;
        
        function print(message) { 
        
          var outputDiv = document.getElementById('output'); 
        
          outputDiv.innerHTML = message; 
        
        } 
        
        for (var s = 0; s < students.length; s += 1) {
          HTML += '<h2>' + 'Student: ' + students[s].name + '</h2>' ;
          HTML += '<p>' + 'Track: ' + students[s].track + '</p>';
          HTML += '<p>' + 'Points: ' + students[s].points + '</p>';
          HTML += '<p>' + 'Achievements: ' + students[s].achievements + '</p>';
               
        };
        
        print(HTML);
<div id="output"></div>

不幸的是,这个代码只有糟糕的结果才是开头的“未定义”。我想摆脱这个。

这是关于我的循环还是其他任何我无法预测的细节?

3 个答案:

答案 0 :(得分:1)

undefined

初始化时,您没有明确地为变量赋值,因此它是+=

第一次使用"undefined"附加到变量时,该值会隐式转换为字符串var HTML = "";

改为使用{{1}}。

答案 1 :(得分:0)

HTML初始化为“”,自undefined(因为未初始化)HTML

以来,您获得undefined
var HTML = ""; //change this line

<强>演示

var students = [
      {
        name: 'Mustafa',
        track: 'A',
        achievements: 5,
        points: 500
      },
      {
        name: 'Ersin',
        track: 'B',
        achievements: 6,
        points: 600
      },
      {
        name: 'Ahmet',
        track: 'C',
        achievements: 7,
        points: 700
      },
      {
        name: 'Mehmet',
        track: 'D',
        achievements: 8,
        points: 800
      },
      {
        name: 'Cafer',
        track: 'E',
        achievements: 9,
        points: 900
      }
    ];

    var HTML = ""; //change this line
    var s = 0;

    function print(message) { 

      var outputDiv = document.getElementById('output'); 

      outputDiv.innerHTML = message; 

    } 

    for (var s = 0; s < students.length; s += 1) {
      HTML += '<h2>' + 'Student: ' + students[s].name + '</h2>' ;
      HTML += '<p>' + 'Track: ' + students[s].track + '</p>';
      HTML += '<p>' + 'Points: ' + students[s].points + '</p>';
      HTML += '<p>' + 'Achievements: ' + students[s].achievements + '</p>';

    };

    print(HTML); 
<div id="output"></div>

答案 2 :(得分:-1)

使用如下所示的空字符串初始化HTML变量:

var HTML="";