我需要使用不同的方法创建 3 个对象。然后我需要将这些对象存储在数组中。然后我需要使用迭代来显示结果。一路上我自己都有点困惑。我没有看到任何结果。我不确定到底出了什么问题。我有一个按钮 onclick 操作,因此您必须单击该按钮才能显示数组....
我是否错误地创建了数组?我在 for 循环中是否错误地访问了数组数据?
html:
<p id="3"></p>
<button onclick="ObjectArray()">click me</button>
JavaScript:
function ObjectArray() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id_num) {
this.firstName = first;
this.lastName = last;
this.id_num = id;
}
var id3 = new employee("joe", "john", "abc123");
//create an array
var IdArray = [id1, id2, id3];
//for loop to display results
var text="";
var i;
for (i = 0; x < IdArray.length; i++){
text += IdArray[i] + "<br>";
document.getElementById("3").innerHTML = text;
}
}
我还想知道如何从另一个函数访问这个数组以用于将来的任务。
最佳答案
你的循环是错误的,最终会无限循环并破坏一切,x
未定义,应该是i
for (i = 0; i < IdArray.length; i++){
text += IdArray[i] + "<br>";
}
document.getElementById("3").innerHTML = text;
另请注意,如果您想要一些文本,则这只会输出 [object Object],实现 toString() 或指定您要访问的对象属性,例如
IdArray[i].firstName
关于javascript - 为数组创建 3 个对象,然后使用迭代 javascript 显示数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32541688/