在中使用for循环遍历对象
looping through an object using a for in
有人能帮我吗?被卡住了一段时间,我所需要做的就是打印出我的对象的属性,有人知道为什么这不起作用吗?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function person(name, dateOfBirth, nationality){
this.name = name;
this.dateOfBirth = dateOfBirth;
this.nationality = nationality;
}
var mark = new person("mark oshea",25,"irish");
var text = "";
for(x in mark) {
text += mark[x];
}
</script>
</body>
</html>
for ... in
循环将遍历给定数组/对象的所有属性。您尝试使用您实际想要的属性来访问您的对象。
在您的情况下,如果您想要属性,text += x;
应该是您想要的。
如果你想获得对象的值,你可以使用forEach
,例如:
mark.forEach( function(value){
text += value;
});
您的html缺少关闭/打开元素,并且您没有声明"var text"。这样试试:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Person</h1>
<p id="person"></p>
<script type="text/javascript">
function person(name, dateOfBirth, nationality){
this.name = name;
this.dateOfBirth = dateOfBirth;
this.nationality = nationality;
}
var text = "";
var mark = new person("mark oshea",25,"irish");
for(x in mark) {
text += mark[x] + " ";
}
var person_paragraph = document.getElementById("person");
person_paragraph.innerHTML = text;
</script>
</body>
</html>
有关DOM函数的更多信息,我建议您仔细阅读mdn。
您的文本变量被捕获在for循环的作用域中。在for循环之外添加这一行可以解决这个问题,如图所示:
http://jsfiddle.net/7z0qonb3/
var text = '';
相关文章:
- 循环遍历以数组为值的Javascript对象
- 循环遍历包含另一个表单的表单
- JS.循环遍历多维数组,以计数元素在每列中的出现次数
- js循环遍历单击的元素子节点
- 根据PHP中数组的长度在Google Maps API中循环遍历标记
- 循环遍历元素jquery选择器
- 无法在javascript中循环遍历对象数组
- 在循环遍历对象 HTMLDivElement 时,应用 ChileNode 样式 zindex 在 firefox 和
- 如何在DataTablesjQuery中循环遍历所有行
- 使用函数for循环遍历对象以更改值,然后返回结果
- 遍历 jQuery:循环遍历子项
- 循环遍历平行层
- 循环遍历 jqGrid 中的 colModels 名称
- jQuery 插件不会循环遍历匹配的项目
- 循环遍历 JSON 对象
- 一次循环遍历一组
- 循环遍历表行,获取总计和更新行
- 循环遍历 DOM 元素时,是否有 for 循环的替代方法
- 使用 ajax、PHP 和 Javascript 循环遍历 JSON 文件
- 循环遍历单选按钮(20 组,每组 3 个),并检查是否选中了每个组