javascript - 问题打印数组的元素

标签 javascript arrays element

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

最佳答案

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

不要忘记 ivar 否则它将在全局范围内定义,我会说考虑一个正确的接口(interface)而不是使用 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(", "))

打印出数组值。

关于javascript - 问题打印数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31631037/

相关文章:

javascript - 如何打开一个而不是使用 .map() 创建的所有 div

javascript - Bootstrap Typeahead 渲染问题

Java - 将类型列表转换为数组

javascript - 为什么对象在 JavaScript 中不可迭代?

node.js - 如何使用 arrayFilters 更新数组中的元素

php - 检查多维数组的每个子数组是否包含元素

javascript - 如何使用 jQuery 在克隆表行后动态更新 ID?

javascript - Angular 服务注入(inject)不一致

javascript - 使用 Underscore JS 对 JSON 数组进行分组和聚合

java - 有任何集合对象可以保存两个以上元素的组合列表吗?