我有一个类似于this one的问题,除了使用Javascript而不是C#。
基本上,我希望能够对表达式进行模式匹配,而不是使用if
语句的长列表,如下所示:
var person.annoyingAction = match([person.gender, person.ageGroup],
[male, child], breakingStuff,
[male, teenager], drivingRecklessly,
[male, adult], beingLazyAfterComingHomeFromWork
[female, child], screechingInAnUnbelievablyHighPitchedVoice,
[female, teenager], knowingEverything,
[female, adult], askingPeopleIfTheyThinkIAmTooFat
[_, baby], cryingEveryTwoHoursAtNight,
[_,_], beingHuman);
有人知道如何在Javascript中实现类似的功能吗?
答案 0 :(得分:1)
我不知道现有的,干净的解决方案,但这是一个简单的实现,与您的示例匹配:
var match = function(target) {
for (i = 1; i < arguments.length; i += 2) {
if (target[0] == arguments[i][0] && target[1] == arguments[i][1]) {
return arguments[i + 1];
}
}
}
使用示例:
var result = match(["Yellow", "Food"],
["Red", "Food"], "Apple",
["Green", "Plant"], "Grass",
["Yellow", "Thing"], "Schoolbus",
["Yellow", "Food"], "Banana",
["Yellow", "Foot"], "Bad"
)
alert(result) # displays "Banana"
在JavaScript中,您无法直接比较数组([1, 2] != [1, 2]
),因此您需要单独比较这些元素。