2014-09-27 35 views
-4

(我是初學者)。如果我想建立一個系統來提問問題並使用if語句和變量返回用戶輸入的答案,將會有大量可能的答案組合,我覺得我將被迫爲每個名字寫出一個變量例如在世界範圍內,然後再做一次,但每個年齡/名稱的組合都有可能,顯然有一個更簡單的解決方案。大多數人如何解決這個問題?如何避免在javascript中編寫數千個變量?

我已經試過這樣:

var yourName = prompt("What's your name?"); 


if (yourName == prompt.value) { 
    console.log("It worked!"); 
} 

它不工作,沒有在控制檯顯示出來。

重要:只有在語句,變量,函數和數組的情況下才可以這樣做嗎?或者我將不得不使用對象和切換語句?

編輯:(這只是關於購物爲例):

function selectPants() { 

    var jeans = "jeans"; 
    var khakis = "khakis"; 

    var yourPants = prompt("What kind of pants do you want?"); 



    if (yourPants == jeans) { 
     console.log("Okay, that will cost $10."), selectShirt(); 
    } 
} 

function selectShirt() { 

    var plaid = "plaid"; 
    var v-neck = "v-neck"; 


    var yourShirt = prompt("What shirt do you want?"); 

    if (yourShirt == plaid) { 
     console.log("Okay, that will cost $5, your total so far is: ??"), selectShoes(); 
    } 
} 


    selectPants(); 

正如你可以看到我還需要一些另外的系統加起來的費用。非常感謝您的幫助!

+1

因爲提示是一個函數,而不是一個對象,並且沒有要訪問的屬性。用戶輸入的值現在存儲在'yourName'變量中;所以你想在這裏測試什麼? – 2014-09-27 13:02:06

+0

您能否提供更多這些「組合」的例子。我懷疑你將會使用if-else語句。 – Mike 2014-09-27 13:14:46

+0

好的,我更新了它,謝謝。 – 2014-09-27 13:35:46

回答

0

一個更好的做法是有問題的對象(對於每個問題)將被存儲在問題集合中。 集合將是JavaScript中的數組。

然後,您可以遍歷每個問題,提示他們並將答案保存回每個問題對象。

// collection of questions. answers are empty to start with 
var questions = [{ "question" : "Whats your name", "answer": ""}, 
       { "question" : "What is your age", "answer": ""}]; 

// Ask all the questions 
for(var i=0,len = questions.length; i < len; i++){ 
    var ans = prompt(questions[i].question); 
    questions[i].answer = ans; // store your answer 
} 

// see what is the answer for the first question. 
console.log(questions[0].answer); 
+0

好吧,我需要知道這一點,但我也想知道是否可以處理變量。非常感謝您的幫助! – 2014-09-27 13:43:42

+0

我沒有看到使用變量的任何特定好處。當你開始將所有內容存儲在變量中。它會變得笨拙。這樣,您可以將所有問題存儲爲JSON字符串,並在需要時加載它們。這也使您有機會編輯程序之外的問題。 – 2014-09-27 13:50:41

0

提示功能不是類,提示。「東西」沒什麼意思,你必須寫提示()

var yourName = prompt("What's your name?"); 
 

 

 
if (yourName == prompt()) { 
 
    console.log("It worked!"); // Open your console to see this 
 
}

+1

而且......你認爲OP在用這段代碼試圖做什麼? – 2014-09-27 13:03:50

+0

**來自問題的引用**設置詢問問題和返回用戶輸入答案的系統_ – Caridorc 2014-09-27 13:07:37

+0

事實上,您編寫的代碼(以及他的問題)與所描述的意圖不相似。 – 2014-09-27 13:08:46