简体   繁体   English

如何使用 DRY 概念更有效地编写此代码?

[英]How can I write this code more efficiently with DRY concept?

This is a piece of a JavaScript code for an HTML form.这是一段用于 HTML 表单的 JavaScript 代码。 I want to be more efficient and not write the same line more than once;我想提高效率,不要多次写同一行; is this possible in the code below?这在下面的代码中可能吗?

function resetOptions(location)
{   
    if (location=='country') 
    {   
        removeOptions(selected_address_zone)
        removeOptions(selected_address_region)
        removeOptions(selected_address_city)
        removeOptions(selected_address_area)
    }
    else if (location=='zone')
    {
        removeOptions(selected_address_region)
        removeOptions(selected_address_city)
        removeOptions(selected_address_area)
    }
    else if (location=='region')
    {
        removeOptions(selected_address_city)
        removeOptions(selected_address_area)
    }
    else
    {
        removeOptions(selected_address_area)
    }
    
}

You could rewrite with a switch statement without breaks.你可以用 switch 语句重写而不中断。 By doing this, if the location is a country, for instance, it will execute the cases below it until it finds a break.通过这样做,例如,如果位置是一个国家/地区,它将执行它下面的案例,直到找到中断为止。

  switch(location): {
    case: 'country': 
        removeOptions(selected_address_zone);
    case 'zone': 
        removeOptions(selected_address_region);
    case 'region':
        removeOptions(selected_address_city);
    default:
          removeOptions(selected_address_area);

  }

You could set variables for the arguments passed in the removeOptions() function at the top of your function.您可以为函数顶部的 removeOptions() 函数中传递的参数设置变量。

You could then adjust the arguments according to your function parameters.然后您可以根据您的函数参数调整参数。

Would be helpful to see the removeOptions() function and its parameters.查看 removeOptions() 函数及其参数会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM