如何检查字符串是否包含数组中的某个元素,而不是其他元素

时间:2016-07-12 10:17:16

标签: javascript arrays

我正在制作一些化学游戏作为JavaScript中的Telegram机器人,你有一个库存,你需要混合正确的化学品。我有一个数组中包含的库存,为了防止通过简单地粘贴您的库存来强行进入某个级别,我需要检查用户输入是否仅包含所需的化学品,而不是任何其他化学品。阵列。

例如:

users[id].inventory = ["Beaker", "Water", "Baking soda", "Heating plate", "Hydrochloric acid"];

if (users[id].level === 1 && 
    msg.text.toLowerCase().indexOf('baking soda') !== -1 &&
    msg.text.toLowerCase().indexOf('hydrochloric acid') !== -1 && 
    msg.text.toLowerCase().indexOf('beaker') === -1 && 
    msg.text.toLowerCase().indexOf('water') === -1 && 
    msg.text.toLowerCase().indexOf('heating plate') === -1) {

    msg.answer("You mix some baking soda with hydrochloric acid.\nSome fun fizzing happens and you produce useless CO2 gas.");
}

在较高级别,您将获得更大的库存,这将以这种方式导致非常大的if语句。这看起来很糟糕,必须有更好的方法。有没有像indexOf()这样的独家解决方案?我已经检查了arr.filter(),但我找不到实现它的好方法。

2 个答案:

答案 0 :(得分:1)

手动检查每种成分并不是一个好主意,因为你指出,如果配方的要求很长而且库存也很长,那将非常繁琐。

我建议创建一个带有两个数组的函数rightIngredients:需求和使用的项目。

考虑到只应该使用配方中的项目,我在函数内部做的第一件事就是检查两个数组的长度。如果它们不同,那么它应该返回false,并且不需要检查任何其他内容。

如果数组的长度相同,那么我们检查用于查看它们是否符合要求的每个项目。如果其中一个不是,那么我们也会返回false。

requirements = ["baking soda", "hydrochloric acid"];

function rightIngredients(req, uses) {
    if (uses.length != req.length) {
    console.log(uses.join(', ')+' are not even the right amount of ingredients');
    missing = true;
  } else {
    var i = 0;
    var missing = false;
    while (i<uses.length && !missing) {
        if (req.indexOf(uses[i].toLowerCase())===-1) missing = true;
      ++i;
    }
    if (missing) console.log(uses.join(', ')+' are not the right ingredients');
    else console.log(uses.join(', ')+' are the right ingredients');
  }
  return !missing;
}
rightIngredients(requirements, ["Beaker", "Baking Soda", "Hydrochloric Acid"]);
// Beaker, Baking Soda, Hydrochloric Acid are not even the right amount of ingredients
rightIngredients(requirements, ["Beaker", "Baking Soda"]);
// Beaker, Baking Soda are not the right ingredients
rightIngredients(requirements, ["Baking Soda", "Hydrochloric Acid"]);
// Baking Soda, Hydrochloric Acid are the right ingredients

答案 1 :(得分:1)

您可以创建所有不允许化学品的数组,然后使用Array.every检查所有元素是否满足此条件。此外,您将根据级别使用不同的组合,因此我建议创建一个级别和不允许的化学品地图,并使该功能通用。

以下是一个示例:

script