寻找一个聪明的 if 条件 - Javascript
Looking for a smart if condition - Javascript
我正在尝试制作一个购买物品的功能,但我不希望人们能够同时收集超过 2 件物品。
我正在寻找类似的条件。
如果 Ax + Sword = true 那么调用函数 buyItem(Dagger)
会说类似 "You cant have more than 2 items".
但考虑到我想稍后添加更多项目。
var buyItem = function (name)
{
if (name === "Axe")
{
console.log("Axe");
}
else if (name === "Sword")
{
console.log("Sword");
}
else if (name === "Dagger")
{
console.log("Dagger");
}
};
谢谢:)
使用一个变量来跟踪您拥有的物品数量怎么样?
int itemsHeld = 0;
获得新物品时使用itemsHeld++;
,失去物品时使用itemsHeld--;
现在,当您尝试购买新商品时,只需询问 if (itemsHeld < 2) getItem();
商店购买计数作为私有变量
// 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');
我正在尝试制作一个购买物品的功能,但我不希望人们能够同时收集超过 2 件物品。
我正在寻找类似的条件。
如果 Ax + Sword = true 那么调用函数 buyItem(Dagger)
会说类似 "You cant have more than 2 items".
但考虑到我想稍后添加更多项目。
var buyItem = function (name)
{
if (name === "Axe")
{
console.log("Axe");
}
else if (name === "Sword")
{
console.log("Sword");
}
else if (name === "Dagger")
{
console.log("Dagger");
}
};
谢谢:)
使用一个变量来跟踪您拥有的物品数量怎么样?
int itemsHeld = 0;
获得新物品时使用itemsHeld++;
,失去物品时使用itemsHeld--;
现在,当您尝试购买新商品时,只需询问 if (itemsHeld < 2) getItem();
商店购买计数作为私有变量
// 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');