这是我的代码。我尝试过很多东西,但它没有用。请不要给我一些复杂的代码,因为我只是javascript中的中级程序员。因此,如果可以的话,尽量让事情尽可能简单。感谢所有帮助的人。
function readNumberOfEntries() {
var entryNumber, numberOfEntries, a;
do {
numberOfEntries = Number(prompt("Enter Value Here"));
if (numberOfEntries < 2) {
alert("Error: Number is not greater than or equal to 2");
}
} while (numberOfEntries < 2);
for (entryNumber = 0; entryNumber < numberOfEntries; entryNumber++) {
a[entryNumber] = Number(prompt("Enter Value"));
a = new Array(numberOfEntries);
document.writeln(a);
}
}
答案 0 :(得分:2)
您的代码的问题在于您在for循环的每次迭代中覆盖数组。这应该可以解决您的问题:
function readNumberOfEntries() {
var entryNumber, numberOfEntries, a;
do {
numberOfEntries = Number(prompt("Enter Value Here"));
if (numberOfEntries < 2) {
alert("Error: Number is not greater than or equal to 2");
}
} while (numberOfEntries < 2);
a = new Array(numberOfEntries);
for (entryNumber = 0; entryNumber < numberOfEntries; entryNumber++) {
a[entryNumber] = Number(prompt("Enter Value"));
}
document.writeln(a);
}
答案 1 :(得分:1)
您应该在分配/添加值之前初始化数组。
function readNumberOfEntries() {
var entryNumber, numberOfEntries, a=[];
do {
numberOfEntries = Number(prompt("Enter Value Here"));
if (numberOfEntries < 2) {
alert("Error: Number is not greater than or equal to 2");
}
} while (numberOfEntries < 2);
for (entryNumber = 0; entryNumber < numberOfEntries; entryNumber++) {
// a = new Array(numberOfEntries);
a[entryNumber] = Number(prompt("Enter Value"));
document.writeln(a);
}
}