0

我想从提示中获取用户的输入,将该输入存储在一个数组中,然后显示它。我只想使用for循环从用户那里获取 10 个输入。我已经尝试过do-while,如下所示。

var givenNames = new Array();
var pattern = /[\w\d]{1,}/ig;

do{
    var name = prompt("Enter some names. Only letters and digits are accepted!\nEntering an empty field stops asking","");
    if(name && name.match(pattern)){givenNames.push(name);}
}
while(name != "");

function displayNames(){
    if(givenNames.length > 0){
        document.getElementById("list").innerHTML = "<span style='color:Navy;font-    weight:bold;'>Given names are:<\/span><br><br>" + givenNames.join("<br><br>");
    } else {
        document.getElementById("list").innerHTML = "<span style='color:Navy;font-weight:bold;'>Nothing has been given!<\/span>";
    }
}

如何用for循环替换它?

4

2 回答 2

1

在此处查看演示

使用您的 for 循环条件来检查计数和输入。

var givenNames = new Array();
var pattern = /[\w\d]{1,}/ig;

var name;

for ( var i=0; i<10 && name != ""; i++){
    name = prompt("Enter some names. Only letters and digits are accepted!\nEntering an empty field stops asking", "");
    if (name && name.match(pattern)) {
        givenNames.push(name);
    }
} 


if (givenNames.length > 0) {
    document.getElementById("list").innerHTML = "<span style='color:Navy;font-    weight:bold;'>Given names are:<\/span><br><br>" + givenNames.join("<br><br>");
} else {
    document.getElementById("list").innerHTML = "<span style='color:Navy;font-weight:bold;'>Nothing has been given!<\/span>";
}

如果您正在do-while使用do {...} while (++count < 10 && name != "")并且如果您想while使用while (count++ < 10 && name != "" ) {...}

于 2013-09-04T19:08:15.673 回答
1
    var givenNames = new Array();
    var pattern = /[\w\d]{1,}/ig;


    for(var i=0;i<10;i++){
var name = prompt("Enter some names. Only letters and digits are accepted!\nEntering an empty field stops asking","");
    if(name && name.match(pattern)){givenNames.push(name);}
    }

    function displayNames(){
        if(givenNames.length > 0){
            document.getElementById("list").innerHTML = "<span style='color:Navy;font-    weight:bold;'>Given names are:<\/span><br><br>" + givenNames.join("<br><br>");
        } else {
            document.getElementById("list").innerHTML = "<span style='color:Navy;font-weight:bold;'>Nothing has been given!<\/span>";
        }
    }

DEMO FIDDLE

于 2013-09-04T19:09:53.717 回答