如何在JavaScript中迭代和打印二维数组?

时间:2014-05-30 04:58:44

标签: javascript html arrays multidimensional-array

我是java脚本的新手,我有这个二维数组,我希望通过for循环将这些数组值传递给链接。我已经发布了以下代码。有人能告诉我怎么做。

由于

<script>
    var MiddelEastCountriesArray = [['Benelux', 'NE'], ['Deutschland', 'DE'], ['France', 'FR'], ['Ireland', 'IE'], ['Italia', 'IE'], ['Nordics', 'NO'], ['Middle East', 'ME'], ['United Kingdom', 'UK']];

    for(var i = 0; i < MiddelEastCountriesArray.length; i++) {
        for(var j = 0; j < MiddelEastCountriesArray[i].length; j++) {

            document.write("<p><a href='http://www.test.com/" + MiddelEastCountriesArray[0][j] + "/default.aspx'>" + MiddelEastCountriesArray[i][0] + "</a></p>");
        }
    }
</script>

预期产出:

        <p><a href='http://www.test.com/NE/default.aspx'>Benelux</a></p>
        <p><a href='http://www.test.com/DE/default.aspx'>Deutschland</a></p>
        <p><a href='http://www.test.com/FR/default.aspx'>France</a></p>
        <p><a href='http://www.test.com/IE/default.aspx'>Ireland</a></p>
        ....
        ....
        ....

3 个答案:

答案 0 :(得分:2)

您不需要迭代内循环。试试这个,

var MiddelEastCountriesArray = [['Benelux', 'NE'], ['Deutschland', 'DE'], ['France', 'FR'], ['Ireland', 'IE'], ['Italia', 'IE'], ['Nordics', 'NO'], ['Middle East', 'ME'], ['United Kingdom', 'UK']];

for(var i = 0; i < MiddelEastCountriesArray.length; i++) {
    document.write("<p><a href='http://www.test.com/" + MiddelEastCountriesArray[i][1] + "/default.aspx'>" + MiddelEastCountriesArray[i][0] + "</a></p>");
}

答案 1 :(得分:0)

不知道,如果它符合您的要求,但如果有一系列物品,那么它就不会感到痛苦。

var MiddelEastCountriesArray = [{place:'Benelux',abbreviation:'NE'},{place:'Detuschland',abbreviation:'DE'}]

现在你可以用这种方式迭代它:

    MiddelEastCountriesArray.forEach(function(x){document.write("<p><a href='http://www.test.com/" + x.abbreviation + "/default.aspx'>" + x.place + "</a></p>");})

答案 2 :(得分:-2)

看起来您只是试图传递第二维的第一个值......

var MiddelEastCountriesArray = [['Benelux', 'NE'], ['Deutschland', 'DE'], ['France', 'FR'], ['Ireland', 'IE'], ['Italia', 'IE'], ['Nordics', 'NO'], ['Middle East', 'ME'], ['United Kingdom', 'UK']];

for(var i = 0; i < MiddelEastCountriesArray.length; i++) {
    for(var j = 0; j < MiddelEastCountriesArray[i].length; j++) {

        document.write("<p><a href='http://www.test.com/" + "" + "/default.aspx'>" + MiddelEastCountriesArray[i][j] + "</a></p>");
    }
}

只需更改你的第二个维度中的第二个参数就像我做的那样......这应该可行