数组for循环,循环次数javascript

时间:2015-09-12 20:56:11

标签: javascript

而不是循环一次显示

id1
id2
id3

它在停止前循环3次。我能做些什么才能让它只循环一次。

HTML:

<p id="show_me"></p>
<button onclick="ObjectArray()">click me</button>

的javascript:

var ObjectArray = function() {
        // 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) {
            this.firstName = first;
            this.lastName = last;
            this.id = id;
        }
        var id3 = new employee("Dallas", "Star", "abc123");

        //create an array
        var IdArray = [id1, id2, id3];

        //for loop to display results
        var text="";
        var i;

        for (i = 0; i < IdArray.length; i++){
            text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
            text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
            text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
        }
        document.getElementById("show_me").innerHTML = text;
}

3 个答案:

答案 0 :(得分:3)

它迭代三次,因为你循环数组的长度,它有3个项目。

如果你想重复&#39;有一次,你可以省略for循环:

text += IdArray[0].firstName + " " + IdArray[0].lastName + " " + IdArray[0].id + "<br>";
text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";

但我认为你真的想这样做:

for (i = 0; i < IdArray.length; i++){
    text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
}

这样你就可以使用它所代表的循环:迭代任何长度的数组,并为数组中的每个项重复一段代码。

答案 1 :(得分:0)

从for循环中删除所有内容,然后添加:

text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";

答案 2 :(得分:0)

一切都很好......但请替换以下代码

 for (i = 0; i < IdArray.length; i++){
        text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";
        text += IdArray[1].firstName + " " + IdArray[1].lastName + " " + IdArray[1].id + "<br>";
        text += IdArray[2].firstName + " " + IdArray[2].lastName + " " + IdArray[2].id + "<br>";
    }

for (i = 0; i < IdArray.length; i++){
        text += IdArray[i].firstName + " " + IdArray[i].lastName + " " + IdArray[i].id + "<br>";

    }