gpt4 book ai didi

javascript - 将提示中的输入存储在数组中并显示该数组

转载 作者:行者123 更新时间:2023-12-02 18:23:14 25 4
gpt4 key购买 nike

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

最佳答案

    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

关于javascript - 将提示中的输入存储在数组中并显示该数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18621625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com