在数组中存储来自提示的输入并显示数组

时间:2013-09-04 18:54:37

标签: javascript html arrays

我想从提示中获取用户的输入,将该输入存储在数组中,然后显示它。我想使用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循环替换它?

2 个答案:

答案 0 :(得分:1)

See demo here

使用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 != "" ) {...}

答案 1 :(得分: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