垂直输出二维数组

时间:2012-10-22 05:14:33

标签: javascript

嘿伙计们,我在这里有一个情况。我有一个代码,它在这里放置二维。

<script>
    Brady = new Array(3);

    for (i = 0; i < Brady.length; ++i) {
        Brady[i] = new Array(5);
    }

    Brady[0][0] = "Team 1";
    Brady[0][1] = "Carol";
    Brady[0][2] = "Greg";
    Brady[0][3] = "Greg";
    Brady[0][4] = "Greg";

    Brady[1][0] = "Team 2";
    Brady[1][1] = "Alice";
    Brady[1][2] = "Peter";
    Brady[1][3] = "Peter";
    Brady[1][4] = "Peter";

    Brady[2][0] = "Team 3";
    Brady[2][1] = "Mike";
    Brady[2][2] = "Bobby";
    Brady[2][3] = "Bobby";
    Brady[2][4] = "Bobby";




    function print_2d_string_array(array) {
        document.writeln("<table border>");

        var row;

        for (row = 0; row < array.length; ++row) {
            document.writeln(" <tr>");

            var col;

            for (col = 0; col < array[row].length; ++col) {
                document.writeln("  <td>" + array[row][col] + "</td>");
            }

            document.writeln(" </tr>");
        }
        document.writeln("</table>");
    }

    print_2d_string_array(Brady);
</script>

输出:

Team 1  Carol   Greg    Greg    Greg
Team 2  Alice   Peter   Peter   Peter
Team 3  Mike    Bobby   Bobby   Bobby

但我想做的是

Team 1  Team 2  Team 3
Carol   Alice   Mike
Greg    Peter   Bobby
Greg    Peter   Bobby
Greg    Peter   Bobby

我花了一个小时才做到这一点,但我运气不好.. plss帮助我。

2 个答案:

答案 0 :(得分:4)

尝试:

<script>
Brady = new Array(3);

for (i = 0; i < Brady.length; ++i) {
    Brady[i] = new Array(5);
}

Brady[0][0] = "Team 1";
Brady[0][1] = "Carol";
Brady[0][2] = "Greg";
Brady[0][3] = "Greg";
Brady[0][4] = "Greg";

Brady[1][0] = "Team 2";
Brady[1][1] = "Alice";
Brady[1][2] = "Peter";
Brady[1][3] = "Peter";
Brady[1][4] = "Peter";

Brady[2][0] = "Team 3";
Brady[2][1] = "Mike";
Brady[2][2] = "Bobby";
Brady[2][3] = "Bobby";
Brady[2][4] = "Bobby";


function print_2d_string_array(array) {
    document.writeln("<table border>");

    var col_len = array.length;
    var row_len = array[0].length;

    for (var i = 0; i < row_len; i++) {
        document.writeln("<tr>");
        for (var j = 0; j < col_len; j++) {
           document.writeln("<td>" + array[j][i] + "</td>");
        }
        document.writeln("<tr>");
    }
    document.writeln("</table>");
}

print_2d_string_array(Brady);​
</script>

这将输出:

Team 1  Team 2  Team 3
Carol   Alice   Mike
Greg    Peter   Bobby
Greg    Peter   Bobby
Greg    Peter   Bobby

这是一个 JSFiddle 示例:http://jsfiddle.net/uNPXa/

答案 1 :(得分:1)

你应该改变你的for循环:

for (row = 0; row < array[0] . length; ++ row)
{
    document . writeln (" <tr>");
    var col;
    for (col = 0; col < array . length; ++ col)
    {
            document . writeln ("  <td>" + array [col][row] + "</td>");
    }
    document . writeln (" </tr>");
}

请注意我在row < array[0] . lengtharray . length

中所做的更改