JavaScript数组“ For Loop”仅打印第一次迭代

时间:2018-11-20 10:09:35

标签: javascript arrays loops printing

JavaScript Arrays在项目符号列表for中打印<ul>循环的第一次迭代,但不打印第二次和第三次迭代。我没有主机服务器;不能使用插件或jQuery;我只能使用HTML和JavaScript。

var businesses = [

  business = [
    "Business1Name",
    "Business1Type",
    "Business1Address",
    "Business1Phone",
    "Business1Url",
    "Business1FB",
    "Business1Owner",
  ],
  business = [
    "Business2Name",
    "Business2Type",
    "Business2Address",
    "Business2Phone",
    "Business2Url",
    "Business2FB",
    "Business2Owner",
  ],
  business = [
    "Business3Name",
    "Business3Type",
    "Business3Address",
    "Business3Phone",
    "Business3Url",
    "Business3FB",
    "Business3Owner",
    "Business3Var",
  ],
];

var text = "<ul>";
for (i = 0; i < businesses.length; i++) {
  for (j = 0; j < businesses[i].length; j++) {
    text += "<li>" + businesses[i][j] + "</li>";
  }
  text += "</ul>";
  text += "<BR>";
}

document.getElementById("businessID").innerHTML = text;
<h2>JavaScript Arrays</h2>
<p id="businessID"></p>

我是新手。先感谢您!在此处https://www.w3schools.com/js/tryit.asp?filename=tryjs_whereto

尝试代码

3 个答案:

答案 0 :(得分:0)

var text = "<ul>";
for(i=0; i< businesses.length; i++){
  for(j=0; j< businesses[i].length; j++){
  text += "<li>" + businesses[i][j] + "</li>";
  }

text += "<BR>";
}
text += "</ul>";
document.getElementById("businessID").innerHTML = text;

答案 1 :(得分:0)

应该在数组中包含值。没有单独的类似表达式的赋值。如果需要键值对,请使用对象。

仅回答您的问题...将text += "</ul>";放在两个for循环之外。它将提供您想要的输出。

但是在数组中有单独的分配不是一个好习惯。

答案 2 :(得分:0)

问题在于,您仅在开始时添加了一个打开的ul标签,但是在for循环中添加了三个关闭的ul标签。这导致第一个列表包含在ul标签中,而其他两个列表则没有。

var text = "<ul>"; // This will create a single opening ul tag
for (i = 0; i < businesses.length; i++) {
  for (j = 0; j < businesses[i].length; j++) {
    text += "<li>" + businesses[i][j] + "</li>";
  }
  text += "</ul>"; // This will create three closing ul tags
  text += "<BR>";
}

要解决您的问题,请在第一个for循环内添加ul标记,以便将其附加到循环的每次迭代中。

var text = "";
for (i = 0; i < businesses.length; i++) {
  text += "<ul>";
  for (j = 0; j < businesses[i].length; j++) {
    text += "<li>" + businesses[i][j] + "</li>";
  }
  text += "</ul>";
  text += "<BR>";
}

您的数组也是非标准的(在方括号内声明变量)。您可能想研究使用具有键/值对的对象。