每个循环中未定义的项目

时间:2014-09-03 17:53:44

标签: javascript jquery loops undefined each

以下代码的每个语句都有一个jquery,它通过一个包含h1,h2 h3,h4的div.faq。根据我的逻辑(现在让我失败),应该通过div运行的代码选择所有Header元素,然后将h1 / h2作为列表项,并将h3 / h4作为子列表项。出于某种原因,我在每个子列表开始之前一直得到一个“未定义”元素。

//Declare everything
var sidebar = "";
var sidebar_header = new Array();
var sidebar_items = new Array();
var i = 0;

//Select all elements
$(".faq h3,.faq h4,.faq h1,.faq h2").each(function(index, value){

    // Add an ID to each element
    $(this).attr("id", "item-" + index);

    //If element is h1 or element is h2
    if($(this).is("h1") || $(this).is("h2")){

        sidebar_header[i] = "<li><a href='#item-" + index + "'>" + $(this).text() + "</a>";

        i++;
    //If element is h3 or is h4
    }else if($(this).is("h3") || $(this).is("h4")){

        sidebar_items[i - 1] += "<li><a href='#item-" + index + "'>" + $(this).text() +" </a></li>";

    }


});


var total = i;

//Loop through all list items and add sub list items
for(i=0;i<total;i++){

    sidebar += sidebar_header[i] + "<ul>" + sidebar_items[i] + "</ul></li>";

}

//Append
$(".side").append("<ul>" + sidebar + "</ul>");

除了我的结果是:

之外,一切都“有效”
List item 1
 - Undefined
 - Sub List item 1
 - Sub List item 2
 - Sub List item 3

List item 2
 - Undefined
 - Sub List item 1
 - Sub List item 2

我不清楚什么是未定义的。一切都被宣布了。我只是在已定义的数组中添加项目。我在代码的不同部分运行了几个console.log,问题似乎在这里:

sidebar_items[i - 1] += "<li><a href='#item-" + index + "'>" + $(this).text() +" </a></li>";

但我无法弄清楚原因。建议欢迎!

更新:

示例链接:http://jsfiddle.net/pgw47ecb/

1 个答案:

答案 0 :(得分:1)

您将字符串连接到没有值的数组索引(嗯,它的值为undefined)。 Javascript很高兴地将undefined转换为字符串并进行连接,因此当您第一次尝试将新HTML添加到该索引时,最终会使用"undefined" + '<li>...</li>'

您需要首先将sidebar_items的每个索引初始化为空字符串(如果未定义该索引的值,则不使用字符串连接)。

$(".faq h3,.faq h4,.faq h1,.faq h2").each(function(index, value){

// Add an ID to each element
$(this).attr("id", "item-" + index);

//If element is h1 or element is h2
if($(this).is("h1") || $(this).is("h2")){

    sidebar_header[i] = "<li><a href='#item-" + index + "'>" + $(this).text() + "</a>";

    i++;
//If element is h3 or is h4
}else if($(this).is("h3") || $(this).is("h4")){
    // Give this index a value: an empty string.
    if(typeof sidebar_items[i - 1] !== "string") sidebar_items[i - 1] = "";

     sidebar_items[i - 1] += "<li><a href='#item-" + index + "'>" + $(this).text() +" </a></li>";

}


});
相关问题