gpt4 book ai didi

Javascript Switch 语句多例返回值

转载 作者:行者123 更新时间:2023-11-30 10:57:20 24 4
gpt4 key购买 nike

我有一个 json 对象,我从中获取数据,其中包含值(奶牛:'是',鸡:'NULL')和(奶牛:'是',鸡:'是')等。我想仅显示具有"is"的值,然后显示它们的值。目前我只能返回包含"is"的第一个案例,例如它只返回“牛”,但目标是返回“牛,鸡”,如果两者都具有"is"值。我在这里做错了什么?或者如果有更好的方法,谢谢您的帮助。

switch ("Yes") {
case popup.properties.Beef: return "<span>Cows</span>";
case popup.properties.Pork: return "<span>Pigs</span>";
case popup.properties.Sheep: return "<span>Sheep</span>";
case popup.properties.Goat: return "<span>Goats</span>";
case popup.properties.Lamb: return "<span>Lambs</span>";
case popup.properties.Rabbit: return "<span>Rabbit</span>";
case popup.properties.OtherMeat: return "<span>Other</span>";
case popup.properties.Chicken: return "<span>Chicken</span>";
case popup.properties.Turkey: return "<span>Turkey</span>";
case popup.properties.Duck: return "<span>Duck</span>";
case popup.properties.Goose: return "<span>Geese</span>";
case popup.properties.Pheasant: return "<span>Pheasants</span>";
case popup.properties.Quail: return "<span>Quail</span>";
case popup.properties.OtherPoultry: return "<span>Other Poultry</span>";
default: return "";
}

最佳答案

您可以获取具有所需值的对象并获取字符串数组。

var values = { Beef: "Cows", Pork: "Pigs", Sheep: "Sheep", Goat: "Goats", Lamb: "Lambs", Rabbit: "Rabbit", OtherMeat: "Other", Chicken: "Chicken", Turkey: "Turkey", Duck: "Duck", Goose: "Geese", Pheasant: "Pheasants", Quail: "Quail", OtherPoultry: "Other Poultry" };
result = Object
.keys(popup.properties)
.filter(k => popup.properties[k] === 'Yes')
.map(k => values[k]);

关于Javascript Switch 语句多例返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59492828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com