首页 > 解决方案 > 在 JavaScript 中添加一个简单的 counter[i] 变量以附加到 wrapper.append(container);

问题描述

这是当前的应用程序:JSFiddle 它目前吐出 31 个半随机但不重复的条目,如下所示:

meal1= undefined,
Plain Pizza,
Hard-boiled egg,
Gluten-free cookie,

meal2= undefined,
Fried Beefcake,
Hard-boiled egg,
Graham Crackers,

meal3= undefined,
Lasagna,
Tater tots,
Sundae,

**看到它在哪里说“未定义”?我正在尝试为其添加一种 day[i] 计数器,这需要(我认为)将另一个数据类型附加到容器 div 中。

我在添加一个按照这些规则发挥作用的附加变量时遇到了很多麻烦。

我尝试过的:嵌套一个 for 循环,该循环会增加每个条目的天数,并将其作为新的 div 附加到脚本底部:

var i = 1;
var day = [];
for (i = 1; i < 32; i++) {
    return day[i] (I don't know...)
} 

这不起作用并且每次都会破坏代码。由于我正在学习,你能提供几种我可以尝试解决这个问题的语法吗?如果你只想修复它,那也没关系。我只是想了解为什么其中一些东西有效。

在 Javascript 代码的底部,我们有:

for (var key in meals){
    container = $('<div id="mealsDiv" class="container"></div>');
    wrapper.append(container);

    //This is where I want to add an extra div class that shows the date (1-31). 

    //I want to append day[i] to the meal and just number them, 1-31. 

    //I tried doing the following but it just breaks everything. 

    container.append('<div class="date">' + day[i] +'</div>');
    container.append('<div class="main">' + meals[key].main +'</div>');
    container.append('<div class="side">' + meals[key].side +'</div>');
    container.append('<div class="dessert">' + meals[key].dessert +'</div>');
}

标签: javascripthtmlarraysappendwrapper

解决方案


You're getting the undefined because day is a number not an array and you're trying to do day[i]

var day = 1;
console.log(x[1]); // undefined

You can simply use the key which is the index of the meal like :

container.append('<div class="date">' + (+key + 1) +'</div>');

the +key is to to cast it to an int and + 1 is because the array index starts from 0

instead of

container.append('<div class="date">' + day[i] +'</div>');

here's your updated fiddle


推荐阅读