Javascript二维数组在打印其他数组之前给出undefined

时间:2015-08-15 12:58:28

标签: javascript html arrays

为什么我在列表项之前打印未定义。不要在我犯错的地方。请帮帮我。请考虑下面的代码段

public class HTTPChatMessageReceiver {

   public HTTPChatMessageReceiver() {
    // TODO Auto-generated constructor stub
   }

   public void handleMessage(ChatMessage message) {

   }

}
var playList = [
      ["Wild Ones", "Flo Rida"],
      ["Wings", "Birdi"],
      ["Pure Love", "White Lion"],
      ["Hold my hands", "Jess Glynn"]
    ];

var listSongs = "</ol>";
 function print(msg)
{
  document.write("<p>" + msg + "</p>");
}

function printSongs( songs )
{
  for(var i = 0; i < songs.length; i++)
    {
      listSongs += "<li>" + songs[i][0] + " " + ", by " + songs[i][1] + "</li>";
    }
  
  listSongs += "</ol>";
  print(listSongs);
}

var box = document.getElementById("container");

document.onLoad(box.innerHTML = printSongs(playList));

为什么在打印未定义的歌曲列表之前。请帮忙

3 个答案:

答案 0 :(得分:1)

打印和打印歌曲实际上并没有返回任何内容,因此它们返回undefined。

更改

 document.write(...stuff...);

 return ...stuff...;

print(listSongs);

return print(listSongs);

答案 1 :(得分:1)

那是因为printSongs函数没有返回任何特定值。如果未指定返回值,则函数将返回值undefined

当您运行load事件中的代码(或至少尝试)时,不应使用document.write。加载页面后,使用document.write会隐式调用window.open,以便创建一个新页面来替换当前页面。

从函数中返回HTML代码而不是将其写出来:

var playList = [
  ["Wild Ones", "Flo Rida"],
  ["Wings", "Birdi"],
  ["Pure Love", "White Lion"],
  ["Hold my hands", "Jess Glynn"]
];

function print(msg) {
  return "<p>" + msg + "</p>";
}

function printSongs(songs) {
  var listSongs = "<ol>"; // should be starting tag, not an ending tag
  for(var i = 0; i < songs.length; i++) {
    listSongs += "<li>" + songs[i][0] + " " + ", by " + songs[i][1] + "</li>";
  }
  listSongs += "</ol>";
  return print(listSongs);
}

// The property is named onload, not onLoad, and it's in the window object
// It's not a function, you assign a function to it
window.onload = function() {
  // get the element inside the load event handler
  var box = document.getElementById("container");
  box.innerHTML = printSongs(playList);
};
<div id="container"></div>

答案 2 :(得分:1)

我认为有些问题:

  • 首次初始化listSongs时,您需要将其设置为<ol>的开始标记,而不是结束标记。所以它应该变成:listSongs = <ol>;
  • 主要问题是document.write函数中的print。您可能不需要这样做,因为您已经期望将box元素的innerHTML设置为由printSongs返回的任何内容填充。
  • 因此,在return中添加printSongs语句,以便在完成循环后返回所有listSongs

代码段:

var playList = [
  ["Wild Ones", "Flo Rida"],
  ["Wings", "Birdi"],
  ["Pure Love", "White Lion"],
  ["Hold my hands", "Jess Glynn"]
];

var listSongs = "<ol>";

function printSongs(songs) {
  for (var i = 0; i < songs.length; i++) {
    listSongs += "<li>" + songs[i][0] + " " + ", by " + songs[i][1] + "</li>";
  }

  listSongs += "</ol>";
  return listSongs;
}

var box = document.getElementById("container");
box.innerHTML = printSongs(playList)
<div id="container"></div>

希望这有帮助。

我还应该补充说,在ol元素中包装p将无效,因为p element only allows inline HTML elements within it and ol is not