2014-12-02 36 views
-2

這裏是我的挑戰:的JavaScript的if/else和比較/關係運算符

  • Complete the canIGet function. This function should:
    • take two arguments:
      • 'item' should represent what the user wants to buy
      • 'money' should represent how many dollars a user has
      • return 'true' if a user can afford a given item according to the price chart below, false otherwise:
        • 'MacBook Air' - $999
        • 'MacBook Pro' - $1299
        • 'Mac Pro' - $2499
        • 'Apple Sticker' - $1
      • return 'false' if the 'item' is not in the above list apple products

(而不是返回真/假我登錄到控制檯)

我會很感激的我是什麼樣的解釋做錯了。

我的代碼:

var canIGet = function(item, money){ 
    if ((money >= 2499) && (item == "Mac Pro" || "Macbook Pro" || "Macbook Air" || "Apple sticker")){ 
     console.log("You can afford a Mac Pro"); 
    } 
    else if ((2499 > money) && (money >= 1299) && (item == "Macbook Pro" || "Macbook Air" || "Apple sticker")){ 
     console.log("You can afford a Macbook Pro"); 
    } 
    else if ((1299 > money) && (money >= 999) && (item == "Macbook Air" || "Apple sticker")){ 
     console.log("You can afford a Macbook Air"); 
    } 
    else if ((999 > money) && (money >= 1) && (item == "Apple sticker")){ 
     console.log("You can afford a Apple sticker"); 
    } else { 
     console.log("Get a job!"); 
    } 
}; 
canIGet("Mac Pro", 1500); 
+0

*執行「我會很感激的我在做什麼錯誤的解釋。」 *是什麼讓你認爲你正在做的事情錯了?你的代碼有問題嗎?它是什麼? – 2014-12-02 18:22:42

+0

爲了檢查我們的答案,有一個摩卡測試。即使在馬克B在答案中提出的建議後,仍然存在問題。 – Tobber 2014-12-02 18:39:27

+0

*「爲了檢查我們的答案,有一個摩卡測試。」*什麼?誰是「我們」?測試在哪裏? *「仍有問題」*如果您不告訴我們,我們無法幫助您。 – 2014-12-02 18:40:12

回答

1

基本的JavaScript(和大多數其他語言):

(item == "Mac Pro" || "Macbook Pro" || "Macbook Air" || "Apple sticker")){ 

沒有測試item針鋒相對的字符串。你正在做一個字符串的邏輯或,然後比較OR結果與項目。

例如它解析/作爲

(item == true || true || true || true) 
(item == true) 
("Sticker" == true) 
true 

你必須把它寫成

if (item == 'Mac Pro') || (item == 'Macbook Pro') || etc... 
+0

啊..謝謝。 – Tobber 2014-12-02 18:28:22