我正在尝试在" name"中存储的提示中要求输入用户名。 var,如果用户什么都没输入,它会从randomName数组中存储的数组中随机选择一个值。但是它既不返回输入的值也不返回数组中的任何内容,它返回的全部是"你的名字是"。为什么呢?
到目前为止
var name=prompt("Please enter a usename");
if(name===" "){
var randomName=["Spill Cramer","Oberon Gorgeous","Pointy Binge","Lord Inquiry","Lower Salmon","Auk Cheeks","Minty Lub","Sonore Dim","African Hernia","Squares Pine","Promise Waterpolo","Cucumber Wizard","Tactful Rampallian","Mars Pawn","Usually Dispatch","Close Baffled","Adaptive Mugger","Involved Neuron","Position Stash","Buttercream Oxidant","Bus Hootenany","Small PHP","Copernicium Hematoma","Nostalgic Relay","Wetsuit Swinhoe"]
var rand=randomName[Math.floor(Math.random()*randomName.length)];
if(rand===0){
alert("Your name is Overfilled Lemon");
}
else{
alert("Your name is "+rand)
}
}
else{
alert("Your name is ",name);
};
答案 0 :(得分:1)
问题是if(name===" ")
只有在用户在提示符中输入空格时才会进入其代码块。将其更改为if(name===""){
,它应该可以正常工作。
答案 1 :(得分:0)
有一些小问题。以下是工作代码。检查这个小提琴。 https://jsfiddle.net/n6oqx441/
var name=prompt("Please enter a usename");
console.log(name)
if(name=== ''){
var randomName=["Spill Cramer","Oberon Gorgeous","Pointy Binge","Lord Inquiry","Lower Salmon","Auk Cheeks","Minty Lub","Sonore Dim","African Hernia","Squares Pine","Promise Waterpolo","Cucumber Wizard","Tactful Rampallian","Mars Pawn","Usually Dispatch","Close Baffled","Adaptive Mugger","Involved Neuron","Position Stash","Buttercream Oxidant","Bus Hootenany","Small PHP","Copernicium Hematoma","Nostalgic Relay","Wetsuit Swinhoe"]
var rand=randomName[Math.floor(Math.random()*randomName.length)];
if(rand===0){
alert("Your name is Overfilled Lemon");
}
else{
alert("Your name is "+rand)
}
}
else{
alert("Your name is "+ name);
};
答案 2 :(得分:0)
从用户体验的角度讲,您可能不希望使用提示作为收集输入的方式。也许您希望查看BootStrap以获得更好的收集输入的方法。
您可能收到错误的原因是,如果用户什么都不输入,则提示的结果实际上为空。
你可能想要做这样的事情:
var name = prompt("enter name: ").trim();
if(!name || name === ""){
//select random name
}
使用trim将删除前导和尾随空白字符,使其更容易进行比较,这意味着如果用户只输入空格,则会为其分配一个随机名称