以正确的方式总结if-loop

Summarize if-loop in the right way

本文关键字:if-loop 方式总      更新时间:2023-09-26

我编写的Javascript代码是为一个小型商店网站的购物车编写的。我知道这段代码非常丑陋,我试着用函数中的参数切换来总结它,但我没有得出一个有效的结论。缩短这段代码的最好方法是什么?

非常感谢!

Javascript:

var pack = '#writePackSummary';
var netPriceOutput = '.writeNetPriceSummary';
var taxPriceOutput = '#writeTaxPriceSummary';
var grossPriceOutput = '#writeGrossPriceSummary'
var netPrice1 = 25;
var netPrice3 = 45.55;
var netPrice6 = 89.10;
var tax = 0.19;
if ($(pack).text() == '1') {
    $(netPriceOutput).text(netPrice1.toFixed(2).toString().replace(/'./g, ','));
    $(taxPriceOutput).text((netPrice1*tax).toFixed(2).toString().replace(/'./g, ','));
    $(grossPriceOutput).text(((netPrice1*tax)+netPrice1).toFixed(2).toString().replace(/'./g, ','));
} else if ($(pack).text() == '3') {
    $(netPriceOutput).text(netPrice3.toFixed(2).toString().replace(/'./g, ','));
    $(taxPriceOutput).text((netPrice3*tax).toFixed(2).toString().replace(/'./g, ','));
    $(grossPriceOutput).text(((netPrice3*tax)+netPrice3).toFixed(2).toString().replace(/'./g, ','));
} else if ($(pack).text() == '6') {
    $(netPriceOutput).text(netPrice6.toFixed(2).toString().replace(/'./g, ','));
    $(taxPriceOutput).text((netPrice6*tax).toFixed(2).toString().replace(/'./g, ','));
    $(grossPriceOutput).text(((netPrice6*tax)+netPrice6).toFixed(2).toString().replace(/'./g, ','));
};

对于初学者,您可以用一个函数替换所有这些.toFixed(2).toString().replace(/'./g, ','):

function stringNum(num) {return num.toFixed(2).replace(/'./g, ',')}
if ($(pack).text() == '1') {
    $(netPriceOutput).text(stringNum(netPrice1));
    $(taxPriceOutput).text(stringNum(netPrice1*tax));
    $(grossPriceOutput).text(stringNum((netPrice1*tax)+netPrice1));
} etc...

也许可以考虑使用switch结构而不是多个if-else ?这也更快,因为它不需要每次都重新创建jQuery对象。

先统一逻辑。找到可能被包装成函数的部分,或者使用线性代码并根据选择读取不同的数据。

例如:

var pack = '#writePackSummary';
var netPriceOutput = '.writeNetPriceSummary';
var taxPriceOutput = '#writeTaxPriceSummary';
var grossPriceOutput = '#writeGrossPriceSummary'
/* declare the prices as array */
var netPrice = {
    1: 25,
    2: 45.55,
    6: 89.10,
};
var tax = 0.19;
/* read the input only once from the element */
var packNr = parseInt( $( pack ).text() );
/* test if a value dataset exists */
if( netPrice[packNr] ) {
    $( netPriceOutput ).text( netPrice[packNr].toFixed(2).toString().replace( /'./g, ',' ) );
    $( taxPriceOutput ).text( (netPrice[packNr]*tax).toFixed(2).toString().replace( /'./g, ',' ) );
    $( grossPriceOutput ).text( ((netPrice[packNr]*tax)+netPrice[packNr]).toFixed(2).toString().replace( /'./g, ',' ) );
}

这将取代三个if条件只用一个,并允许快速添加其他价格。

更进一步,识别更多彼此重复的代码部分,并将逻辑组合在可重用的部分(即函数/方法)中。例如《Scimonster》的答案便是"next step"。