寻找一个聪明的if条件 - Javascript

时间:2015-02-13 23:05:43

标签: javascript if-statement conditional-statements

我正在努力购买物品,但我不希望人们能够同时收集超过2件物品。

我正在寻找一种陈述类似的条件。

如果Ax + Sword = true,则调用函数buyItem(Dagger)会说“你不能超过2项”。

但请考虑我想稍后添加更多项目。

var buyItem = function (name)
{
    if (name === "Axe")
    {
        console.log("Axe");
    }
    else if (name === "Sword")
    {
        console.log("Sword");

    }
    else if (name === "Dagger")
    {
        console.log("Dagger");
    }
};

谢谢:)

2 个答案:

答案 0 :(得分:1)

如何使用变量来跟踪您拥有的项目数量?

int itemsHeld = 0;

当您获得新项目时,请使用itemsHeld++;,当您丢失一项时使用itemsHeld--;

现在,在尝试获取新项目时,您只需询问if (itemsHeld < 2) getItem();

即可

答案 1 :(得分:0)

将已购买的商店计为私人变量

&#13;
&#13;
// store reference to your function returned from self invoking anonymous function enclosure (to prevent internal vairables from leaking into global scope)
var buyItem = (function(){
  // store local reference to number of items already bought
  var bought = 0;
  // return the function to be assigned to buyItem
  return function (name)
  {
    // if we reached the maximum, don't buy any more - just log a warning and return
    if(bought >= 2){
      console.log("your hands are full!!");
      return;
    } else {
      // otherwise increment the bought counter
      bought++;
    };
    if (name === "Axe")
    {
        console.log("Axe");
    }
    else if (name === "Sword")
    {
      console.log("Sword");
    }
    else if (name === "Dagger")
    {
      console.log("Dagger");
    }
  };
})();

// try it out
buyItem('Dagger');
buyItem('Sword');
buyItem('Axe');
&#13;
&#13;
&#13;