2016-06-08 58 views
0

我試圖在存儲在「name」var中的提示中詢問用戶名,如果用戶什麼都不輸入,它會隨機選擇來自存儲在randomName數組中的數組的值。但它不返回數組中輸入的值或任何內容,它返回的是「您的名字是」。爲什麼?如何獲取此提示的值並將其放入if/else語句

這是迄今爲止

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); 
}; 
+1

如果用戶什麼都不輸入,那麼'name'將等於'''',而不是''''' – Hamms

回答

1

的問題是,如果用戶輸入一個空格進入提示if(name===" ")只會進入它的代碼塊。將其更改爲if(name===""){並且它應該正常工作。

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); 
}; 
0

從UX角度來說,你可能不希望被使用的提示,以此來收集輸入,也許你想看看系統啓動時進行收集輸入一個更好的方式。

您可能會收到錯誤的原因是,如果用戶什麼都不輸入,提示的結果實際上是空的。

很可能,你需要做這樣的事情:

var name = prompt("enter name: ").trim(); 
if(!name || name === ""){ 
//select random name 
} 

使用修剪將刪除開頭和結尾的空白字符使其更對比較容易,這意味着如果用戶在哪裏只有輸入空格,該會被分配一個隨機名稱

相關問題