Javascript生成的HTML也打印“undefined”

时间:2012-10-08 08:34:34

标签: javascript html

我试图制作一个菜单,其中包含从last.fm API中提取的艺术家姓名和图片。目前,它生成图像列表和名称,但它打印" undefined"在列表的顶部。我已经尝试用艺术家名称/图像来评论填充元素的部分,并且只是让它生成元素,但它仍然打印未定义。我完全不知道它的说法是不确定的。

首先,它进行AJAX调用以获取所需的信息:

  if (window.XMLHttpRequest) { // Non-IE browsers
httpRequest = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

httpRequest.open("GET", 'http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=b25b959554ed76058ac220b7b2e0a026&format=json', true);

httpRequest.onreadystatechange = function () {
var done = 4, ok = 200;
// Parse the JSON into JavaScript immediately on receipt
if (httpRequest.readyState == done && httpRequest.status == ok) {
  artistList = JSON.parse(httpRequest.responseText);

然后它处理该信息并生成它使用inner.HTML实现的HTML

var artistsAndImage = {};

for (var i=0; i < artistList["artists"]["artist"].length; i++) {
var name = artistList["artists"]["artist"][i]["name"];
artistsAndImage[name] = artistList["artists"]["artist"][i]["image"][0]["#text"];
};
var code;
// Generate HTML for sidebar with artist names and iamges
for (var name in artistsAndImage) {
nameid = name.
      replace(/ /g, "_").
      replace(/&/g, ":amp").
      replace(/\+/g, ":plus");
code += "<element id=\"" + nameid + "\" onclick=\"details(this)\">\n<p style = \"cursor:default\">\n <img src=\"" + artistsAndImage[name] + "\" alt=\"alt\" width = \"50\" height = \"50\">\n" + name + "\n</p> </element>\n";
};
 document.getElementById("sidebar").innerHTML = "<div style = \"padding:20px\">" + code + "</div>";

&#34; undefined&#34;来自,我该如何解决?您可以在此处查看上传页面的当前版本:http://test.yukot.corp.he.net/

2 个答案:

答案 0 :(得分:0)

使用空字符串实例化var code;

var code = '';

答案 1 :(得分:0)

乍一看,我可以看到undefined出现的三个可能原因,artistList["artists"]["artist"][i]["image"][0]["#text"]并不总是存在(此行artistsAndImage[name] = artistList["artists"]["artist"][i]["image"][0]["#text"];
之后,您定义了一个变量code,但其值(自动)设置为undefined,您不会将其初始化为字符串:var code = '';应解决该问题。
另一种解释是你循环遍历对象,而不检查你正在处理的属性是否在实例本身上定义:

var code = ''; //initialize code to empty string
for (var name in artistsAndImage)
{
    if (artistsAndImage.hasOwnProperty(name))
    {
        code += 'First string';
        //only process those that are instance properties
    }
}

要绝对确定,您也可以检查undefined

var code = '';
for (var name in artistsAndImage)
{
    if (artistsAndImage.hasOwnProperty(name) && artistsAndImage[name] !== undefined)
    {
        //only process those that are instance properties
    }
}

在您的控制台中尝试此操作:

var code;//code is set to undefined
code += 'part of a string';
console.log(code);//logs: undefinedpart of a string