0

我创建了一个字符串数组,格式为“monthX”,其中是一个在整个数组中增加的数字。

我有一个函数,我试图引用数组的特定项目,但它一直以未定义的形式出现。这是我的代码:

function listCategories() {
    categoryList.innerHTML = ""

    for (var propertyName in categoryObject) {
        var rowHTML = "<div>"
        rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
        rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
        rowHTML += "</div>"
        categoryList.innerHTML += rowHTML
    }
}

//Months to load in
for (var i=0; i<24; i++) {
    monthList[i] = "month" + (i + startingMonth)
}

我感兴趣的区域是“monthList[3]”行。即使我 console.log(monthList[3]) 它正确地说“month6”,它仍然未定义。有任何想法吗?我的代码中有错误吗?

4

2 回答 2

0

好吧,两个问题:你什么时候叫“listCategories()”?在设置月份列表之前还是之后?

而且,你有没有先为monthList设置全局?

    //globalize monthList array to be usable in functions
var monthList;

function listCategories() {
    categoryList.innerHTML = ""

    for (var propertyName in categoryObject) {
        var rowHTML = "<div>"
        rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
        rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
        rowHTML += "</div>"
        categoryList.innerHTML += rowHTML
    }
}

//Months to load in
for (var i=0; i<24; i++) {
    monthList[i] = "month" + (i + startingMonth)
}

//do NOT CALL listCategories prior this line!!

那应该做

于 2013-02-05T00:35:19.277 回答
0

在您向我们展示的代码中,您从未将其声明monthList或定义为数组。

function listCategories() {
    categoryList.innerHTML = ""

    for (var propertyName in categoryObject) {
        var rowHTML = "<div>"
        rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
        rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
        rowHTML += "</div>"
        categoryList.innerHTML += rowHTML
    }
}

var monthList = [],
    startingMonth = 1;

//Months to load in
for (var i=0; i<24; i++) {
    monthList[i] = "month" + (i + startingMonth)
}

请注意我在函数定义之后、循环之前添加的附加行。

于 2013-02-05T00:35:53.167 回答