如何将提示中的字符串输入数组?

How to enter the strings from prompt into an array?

这是我的代码。我尝试了很多东西,但没有用。请不要给我一些复杂的代码,因为我只是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);
                }
            }

你应该在 assignment/adding 值进入它之前初始化你的数组。

      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);
            }
        }

您的代码存在的问题是您在 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);
}