我创建了一个字符串数组,格式为“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”,它仍然以未定义的形式进入。有任何想法吗?我的代码中有错误吗?
答案 0 :(得分:0)
嗯,有两个问题: 什么时候叫“listCategories()”? 在设置monthList之前或之后?
并且,您是否先设置了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!!
应该这样做
答案 1 :(得分: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)
}
注意我在函数定义之后但在循环之前添加的其他行。