我有以下代码 -
<script type="text/javascript">
function test() {
var results = "";
var myArray = new Array();
myArray[0] = "Customizable";
myArray[1] = "Marketing Collateral";
myArray[2] = "Online Marketing";
myArray[3] = "Training";
myArray[4] = "Event Resources";
myArray[5] = "Marketing Logos";
myArray[6] = "Competitive Solution Comparison";
myArray[7] = "Sales Tools";
myArray[8] = "Retail Marketing"
myArray[9] = "Internal";
results = "<table>";
for (var i=0; i<myArray.length; i++) {
results += "<tr><td>" + myArray[i] + "</td>";
results += "<td>" + myArray[i+1] + "</td></tr>";
}
results += "<tr><td colspan=2><a href='#' onclick='javascript:RedirectParentToDownload();'>View all content ></a></td></tr>";
results += "<table><br /> <br />";
var div = document.getElementById("associatedAssets");
div.innerHTML = results;
}
</script>
<body onload="javascript:test();">
<div id="associatedAssets"></div>
</body>
如何将输出呈现为2列和n行?我希望输出看起来像这样 -
Customizable Marketing Collateral
Online Marketing Training
Event Resources Marketing Logos
etc
答案 0 :(得分:1)
如果您将循环更改为:
for (var i=0; i<myArray.length; i=i+2) {
然后你的代码基本上有效。但是,您需要检查myArray[i+1]
是否存在,以便它也适用于奇数个元素。
答案 1 :(得分:1)
Here它正在工作和修复。
在这里你必须跳过第二个数字,因为有2列
for (var i = 0; i < myArray.length; i+=2 )
您还必须检查第二个元素。如果数组中的元素甚至没有问题,它们可以除以2.如果它是奇数,则调用不存在的元素。使用ternary operator
检查是否未定义( myArray[i+1]===undefined ? '' : myArray[i+1] )
或更简单
( myArray[i+1] || '' )
答案 2 :(得分:0)
你需要在你的for循环中使用i的增量为2 在将数组内容连接到HTML字符串时,还要在使用它之前添加一个检查以查看第i + 1个元素是否存在。
试试这个:
function test() {
var results = "";
var myArray = new Array();
myArray[0] = "Customizable";
myArray[1] = "Marketing Collateral";
myArray[2] = "Online Marketing";
myArray[3] = "Training";
myArray[4] = "Event Resources";
myArray[5] = "Marketing Logos";
myArray[6] = "Competitive Solution Comparison";
myArray[7] = "Sales Tools";
myArray[8] = "Retail Marketing"
myArray[9] = "Internal";
results = "<table>";
for (var i=0; i<myArray.length; i=i+2) { //###NOTICE THE CHANGE FROM i++ TO i=i+2
results += "<tr><td>" + myArray[i] + "</td>";
if(i+1 < myArray.length){
results += "<td>" + myArray[i+1] + "</td></tr>";
} else{
results += "<td></td></tr>";
}
}
results += "<tr><td colspan=2><a href='#' onclick='javascript:RedirectParentToDownload();'>View all content ></a></td></tr>";
results += "<table><br /> <br />";
var div = document.getElementById("associatedAssets");
div.innerHTML = results;
}