当前位置: 代码迷 >> JavaScript >> 发行数组的打印元素
  详细解决方案

发行数组的打印元素

热度:84   发布时间:2023-06-05 09:28:45.0

我是编程和堆栈溢出的新手,请原谅我的胡言乱语。请打印最后三个数组时出现问题。 它只打印出数组中的最后一个元素。但是当我使用console.log时,它会打印出所有元素。我希望我有道理。 请帮助。 任何帮助将不胜感激。 谢谢

    <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="">
    </head>


    <body>
      <h1>Score Sheet</h1>
      <script type="text/javascript">
      var candidateName = [];
      var candidates = 0;
      var moreCandidates = "y";

      while (moreCandidates == "y"){
        candidateName.push(prompt("Enter candidate name"));
        var noOfSubjects = prompt("How many subjects are you offering?");

        for(i = 1; i <= noOfSubjects; i++){
          var subName = [];
          var scores = [];
          var unit = [];
          subName.push(prompt("What is the subject name?"));
          console.log(subName);
          scores.push(prompt("Enter your subject score"));
          console.log(scores);
          unit.push(prompt("Enter your subject unit"));
          console.log(unit);
        }

        moreCandidates = prompt("Do you want to add more candidates? y/n");
        candidates++
     }

     document.write("Number of candidates is" + " " + candidates);
     document.write("<br/>");
     document.write(candidateName);
     document.write("<br/>");
     document.write(noOfSubjects);
     document.write("<br/>");
     document.write(subName);
     document.write("<br/>");
     // document.write(scores);
     // document.write("<br/>");
     // document.write(unit);

   </script>

问题是您要为每次循环迭代重置数组,以便它们仅包含一个值。 而是在循环外声明它们。

不要为i忘记var ,否则它将在全局范围内定义,我想说的是考虑一个适当的接口,而不是使用prompt()获取之后的值,它将提供更好的用户体验。

var subName = [];
var scores = [];
var unit = [];

for(var i = 1; i <= noOfSubjects; i++){
    subName.push(prompt("What is the subject name?")); 
    console.log(subName);
    scores.push(prompt("Enter your subject score"));
    console.log(scores);
    unit.push(prompt("Enter your subject unit"));
    console.log(unit);
}

如果要使用文档编写,则可以简单地使用如下所示

document.write(scores.join(", "))

打印出数组值。

我相信(我尚未测试过)必须使用循环才能将document.write与数组配合使用:

for(var i = 0; i < candidateName.length; i++)
{
    document.write(candidateName[i]);
}

看看这些:

  相关解决方案