gpt4 book ai didi

javascript - 问题打印数组的元素

转载 作者:行者123 更新时间:2023-12-03 09:27:16 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com