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



我是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>
        ....
        ....
        ....

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

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>");
}

不知道它是否符合你的要求,但如果有一个对象数组,那么它不会很痛苦。

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>");})

相关内容

  • 没有找到相关文章

最新更新