Javascript Switch Statement多个情况下返回值

问题描述 投票:0回答:1

[我有一个json对象,我正在使用值(Cow:'是',Chicken:'NULL')和(Cow:'Yes',Chicken:'Yes')等来获取数据。我想显示仅具有“是”的值,然后是其值。目前,我只能返回包含“是”的第一种情况,例如,它仅返回“牛”,但是如果两者都具有“是”值,则目标是返回“牛,鸡”。我在这里做错了什么?或者,如果有更好的方法,谢谢您的帮助。

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 "";
}
javascript json if-statement switch-statement conditional-statements
1个回答
0
投票

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

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]);
© www.soinside.com 2019 - 2024. All rights reserved.