簡體   English   中英

發行數組的打印元素

[英]Issue printing elements of the arrays

我是編程和堆棧溢出的新手,請原諒我的胡言亂語。請打印最后三個數組時出現問題。 它只打印出數組中的最后一個元素。但是當我使用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);
}

如果要使用文檔編寫,則可以簡單地使用join()如下所示

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

打印出數組值。

我相信(我尚未測試過)必須使用循環才能將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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM