简体   繁体   English

更改 if else 以切换 case 语句

[英]Change if else to switch case statement

I have a function with some if…else like this:我有一个 function 和一些 if…else like this:

function updateInputs(data) {
  from = data.from;
  to = data.to;
  rangeInput = $(data.input);
  
  if (rangeInput.hasClass('rangeSalary')) {
    $inputFromSalary.prop("value", from);
    $inputToSalary.prop("value", to);      
  } else if (rangeInput.hasClass('rangeAge')) {
    $inputFromAge.prop("value", from);
    $inputToAge.prop("value", to);
  }
  
  table.draw();
}

But I need to add more statements, so I think it is better to use switch…case, so I tried to do this:但是我需要添加更多的语句,所以我认为最好使用 switch...case,所以我尝试这样做:

function updateInputs(data) {
  from = data.from;
  to = data.to;
  rangeInput = $(data.input).hasClass('rangeSalary');

  switch (rangeInput) {
    case 'rangeSalary':
      $inputFromSalary.prop("value", from);
      $inputToSalary.prop("value", to);
      break;
    case 'rangeAge':
      $inputFromAge.prop("value", from);
      $inputToAge.prop("value", to);
      break;
  }

  table.draw();
}

But it didn't work.但它没有用。 What am I missing?我错过了什么?

The problem with your code is that the result you're getting from hasClass will be either true or false , neither of which matches any of your case labels.您的代码的问题是您从hasClass获得的结果将是truefalse ,它们都不匹配您的任何案例标签。

If notice that the only thing that's different in the code in the if / else if blocks (or case s) is the jQuery object that you call prop on.如果注意到if / else if块(或case s)中的代码唯一不同的是您调用prop的 jQuery object 。 That being the case, I would lean toward having a map (or object) of those keyed by their name.在这种情况下,我倾向于拥有一个以他们的名字为键的 map(或对象)。 The name could be from the name attribute (if this is a type of element that allows name and if it makes sense), or a data-name attribute (since you can put a data-* attribute on any element).名称可以来自name属性(如果这是一种允许name并且有意义的元素类型),也可以来自data-name属性(因为您可以将data-*属性放在任何元素上)。 For instance:例如:

<input data-range="Salary" ... >
<input data-name="rangeFromSalary" ... >
<input data-name="rangeToSalary" ... >
<input data-range="Age" ... >
<input data-name="rangeFromAge" ... >
<input data-name="rangeToAge" ... >
const rangeInputs = new Map($("[data-name]").map((i, input) => {
    return [input.getAttribute("data-name"), $(input)];
}));
function updateInputs(data) {
    // Note: You need to declare `from` and `to`
    const from = data.from;
    const to = data.to;
    // Get the name for this input
    const rangeName = data.input.getAttribute("data-range");
    // Get the matching jQuery objects
    const rangeFrom = rangeInputs.get(`rangeFrom${inputName}`);
    const rangeTo   = rangeInputs.get(`rangeTo${inputName}`);
    // Got them?
    if (rangeFrom && rangeTo) {
        // Set them
        rangeFrom.prop("value", from);
        rangeTo.prop("value", to);
    }
  
    table.draw();
}

Note that I added declarations for from and to .请注意,我添加了fromto声明。 Without them, your code was falling prey to what I call The Horror of Implicit Globals .没有它们,你的代码就会沦为我所说的隐式全局恐怖的牺牲品。 Always declare your variables.总是声明你的变量。


In a comment you seemed to worry about using ES2015+ features.在评论中,您似乎担心使用 ES2015+ 功能。 Here's the above using only ES5 and below features:以下是仅使用 ES5 及以下功能的上述内容:

var rangeInputs = Object.create(null);
$("[data-name]").each((i, input) => {
    rangeInputs[input.getAttribute("data-name")] = $(input);
});
function updateInputs(data) {
    var from = data.from;
    var to = data.to;
    // Get the name for this input
    var rangeName = data.input.getAttribute("data-range");
    // Get the matching jQuery objects
    var rangeFrom = rangeInputs.get(`rangeFrom${inputName}`);
    var rangeTo   = rangeInputs.get(`rangeTo${inputName}`);
    // Got them?
    if (rangeFrom && rangeTo) {
        // Set them
        rangeFrom.prop("value", from);
        rangeTo.prop("value", to);
    }
  
    table.draw();
}

But if you really, really want to use switch :但如果你真的,真的想使用switch

function updateInputs(data) {
    var from = data.from;
    var to = data.to;
    var rangeFrom, rangeTo;
    switch (data.input.getAttribute("data-range")) {
        case "rangeSalary":
            rangeFrom = $("rangeFromSalary");
            rangeTo = $("rangeToSalary");
            break;
        case "rangeAge":
            rangeFrom = $("rangeFromAge");
            rangeTo = $("rangeToAge");
            break;
        // ...
    }
    if (rangeFrom && rangeTo) {
        rangeFrom.prop("value", from);
        rangeTo.prop("value", to);
    }
  
    table.draw();
}

But notice that now, you have the names in two places (the HTML and the code), not just in one place (the HTML).但请注意,现在您在两个地方(HTML 和代码)有名称,而不仅仅是在一个地方(HTML)。 That invites the case where you add or remove them in one place but not the other.这会导致您在一个地方添加或删除它们而不是另一个地方。

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

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