javascript - 在 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>');
}
解决方案
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
推荐阅读
- javascript - 如何保存 HTML FORM 数据以供将来使用
- javascript - 使用 sessionStorage 将值存储在数组中
- azure - 如何使用 powershell、Azure CLI 或 Terraform 更新 Azure AD 应用注册中的 Knownclientapplications
- c - 什么是一维字符串数组?
- ruby-on-rails - Mongoid unscoped find 抛出未找到错误
- scala - Scala 地图未更新
- hadoop - 如何在 Hive 3.1 上为 DynamoDB 创建外部表
- javascript - 在家里我得到那个错误:任何导航器都没有处理带有有效负载 {"params":{"company":"Marciello Resto 2"}} 的操作 'SET_PARAMS'
- python - 如何从 Dockerfile 安装 Python 3.7 和 Pip
- c# - 无法让 GetPositionFromPoint 正常工作(WPF、C#)