javascript - 将其放入函数JS

标签 javascript function conditional-statements

有一个条件,但是很麻烦,怎么减少呢?或者编写一个函数,将有一个上诉。

if (obj.Language.code == "ru") {
        if (obj.Tariff.typeCalc != 1) {
            if (obj.Price.Discount) {
                t = t + getText(obj.Language.code, 'PriceWithDiscount', [Round(obj.Price.Itog), final_currency]);
            }
            else {
                t = t + getText(obj.Language.code, 'PriceNoDiscount', [Round(obj.Price.Itog), final_currency]);
            }
        }
        else {
            if (obj.Price.Discount) {
                t = t + getText(obj.Language.code, 'PriceWithDiscount', [Round(obj.Price.Itog), obj.Currency.symbol]);
            }
            else {
                t = t + getText(obj.Language.code, 'PriceNoDiscount', [Round(obj.Price.Itog), obj.Currency.symbol]);
            }
        }

设计

if (obj.Language.code == "ru") {
}
else {
}

会经常见面,不想堆积

if (obj.Language.code == "ru") {
            if (obj.Price.Discount) {
                
                t = t + getText(obj.Language.code, 'PriceWithDicountOutCity', [obj.Price.Itog, final_currency, Round(obj.Len.value, final_currency), nextkmprice]);
            }
            else {
                
                t = t + getText(obj.Language.code, 'PriceOutCity', [obj.Price.Itog, final_currency, Round(obj.Len.value, final_currency), nextkmprice]);
            }
        }
        else {
            if (obj.Price.Discount) {
                
                t = t + getText(obj.Language.code, 'PriceWithDicountOutCity', [obj.Price.Itog, obj.Currency.symbol, Round(obj.Len.value, obj.Currency.symbol), nextkmprice]);
            }
            else {
                
                t = t + getText(obj.Language.code, 'PriceOutCity', [obj.Price.Itog, obj.Currency.symbol, Round(obj.Len.value, obj.Currency.symbol), nextkmprice]);
            }
        }

最佳答案

您可以采用单个外部检查和两个条件。

if (obj.Tariff.typeCalc != 1) {
    t += getText(
        obj.Language.code,
        obj.Price.Discount ? 'PriceWithDiscount' : 'PriceNoDiscount',
        [
            Round(obj.Price.Itog),
            obj.Language.code == "ru" ? final_currency : obj.Currency.symbol
        ]
    );
}

对于最后一个问题,您可以预先存储currency并使用变量而不是多个条件语句。

var currency = obj.Language.code == "ru" ? final_currency : obj.Currency.symbol;

t += getText(
    obj.Language.code,
    obj.Price.Discount ? 'PriceWithDicountOutCity' : 'PriceOutCity',
    [
        obj.Price.Itog,
        currency,
        Round(obj.Len.value, currency),
        nextkmprice
    ]
);

关于javascript - 将其放入函数JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52643927/

相关文章:

javascript - wysihtml5编辑器中的特殊符号

c - C 中传递给函数之前和之后 sizeof(array) 之间的差异

Python迭代不进入if-elif

r - 如何从 R 中的包中提取信息并在函数中使用?

C:Turbo C 编译器中 for 循环的异常行为

javascript - 在条件语句中递增变量

javascript - 新闻源的 React 架构

javascript - 音频标签在 chrome 中有效,但在 Firefox 中无效

javascript - JavaScript 输出中的 CoffeeScript 注释

c - 从结构体中的函数指针访问数据成员