1

我目前正在进行文字冒险。我正在实现一个功能,如果你有某个物品,你可以用它来换取游戏中的提示。我只是无法弄清楚如何在背包中搜索该项目,以便正确的提示会显示出来。

以下是声明:

case "drift wood":
case "soda can":
    case "shell":
        case "fork":
if(mapLocation === 9)
{
    gameMessage = "Weren't there some loose planks in that sunken ship?";

    backpack.splice(backpackIndexNumber, 1);
}
else if(mapLocation === 9)
{
    gameMessage = "That trench sure was dark.";

    backpack.splice(backpackIndexNumber, 1);
}
else if(mapLocation === 9)
{
    gameMessage = "That loose sand on the beach sure looks like fun to dig into.";
    backpack.splice(backpackIndexNumber, 1);
}
else if(mapLocation === 9)
{
    gameMessage = "A treasure chest needs unlocking.";
    backpack.splice(backpackIndexNumber, 1);
}
break;

对于第一个 if(mapLocation === 9),我需要该程序在背包中搜索撬棍以获得“在那艘沉船中没有松动的木板吗?” 信息。

我的背包变量是这样的:

var backpack = [];
4

1 回答 1

1

如果你的背包数组只包含字符串“crowbar”,那么你可以这样做:

hasCrowbar = backpack.indexOf("crowbar") > -1;

另一方面,如果您的背包包含这样的对象:

var backpackObj = [ 
    {
      item: "thing1",
      weight: 10
    }, 
    {
      item: "crowbar",
      weight: 20
    }
  ];

然后我会使用 lodash,并像这样检查它:

hasCrowbarObj = _.filter(backpackObj, function(b){
  return b.item === "crowbar";
}).length > 0;

这是一个jsfiddle:

https://jsfiddle.net/mckinleymedia/uf74d9sb/1/

于 2015-12-17T05:22:54.147 回答