我想从提示中获取用户的输入,将该输入存储在数组中,然后显示它。我想使用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
循环替换它?
答案 0 :(得分: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 != "" ) {...}
答案 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 强>