发出阵列的打印元素

时间:2015-07-25 20:55:22

标签: javascript arrays elements

我是编程和堆栈溢出的新手,所以原谅我的胡言乱语。请问我打印出最后三个阵列的问题。它打印出数组中的最后一个元素。但是当我使用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>

2 个答案:

答案 0 :(得分:1)

问题是您是为每个循环迭代重置数组,因此它们只会包含一个值。在循环之外声明它们。

请勿忘记var i,否则会在全局范围内定义,我会说考虑一个合适的界面,而不是使用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);
}

如果您想使用文档编写,只需使用

中的join()即可

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

打印出数组值。

答案 1 :(得分:0)

我相信(我还没有对此进行过测试)你必须使用循环来将document.write与数组一起使用:

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

看看这些:

http://www.w3schools.com/js/js_loop_for.asp

http://www.w3schools.com/js/js_arrays.asp