检查输入是否在两个值之间(多个条件) [英] Check if input is between two values (multiple conditions)

查看:71
本文介绍了检查输入是否在两个值之间(多个条件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个项目,需要读取可以采用不同格式的数字,并对照用户输入检查这些数字.在某些情况下,这将是一个间隔,例如"8800-9000",在某些情况下,它将是一个4位数的数字,在某些情况下将是5位数的数字.

I am making a project where I need to read in numbers that can be in different format and check these against the users input. In some cases this will be an intervall like "8800-9000", in some cases it will be a 4-digit number, in some cases a 5-digit number.

该数组如下所示:

var testArray = [
{
    "label": "Nordea",
    "value": ["1100-1199", "1400-2099", "3000-3399", "3410-4999"]
},
{
    "label": "Swedbank",
    "value": ["7000-7120", "7123-8104", "8106-8999"]
},
{
    "label": "Sparbanken Nord",
    "value": "8264"
},
{
    "label": "Sparbanken i Enköping",
    "value": ["7121-7122", "8305-5"]
}];

我制作了一个巨大的嵌套if-mess,效果还不错.我唯一的问题是找到匹配项时它不会中断.如果我输入"8305-5",它将在2个不同的对象属性数组中找到一个匹配项.我是否设计了之间"功能错误?

I've made a huge nested if-mess that works kind of OK. My only issue is that its not breaking when it finds a match. If i input "8305-5" it will find a match in 2 different object property arrays. Have I designed the "between"-function wrong?

我还可以搜索比间隔大得多的数字,并且仍然可以找到匹配项.时间间隔"3410-3999"在一个数组中,如果我搜索"39999",它仍然会匹配.

Also I can search for numbers that are way bigger than the intervalls and still get a match. Intervall "3410 - 3999" is in an array, and if I search for "39999" it will still get a match.

非常感谢所有帮助!

我遍历数组中的所有对象,如果值属性是一个数组,我将检查每个元素的长度,以查看是否应匹配介于"值或直接的"===匹配项

I iterate over all objects in the array, and if the value-property is an array I will check the lenght of each element to see if I should match a "between"-value or a straight "===" match.

如果不是数组,则尝试简单匹配.

If its not an array I try a simple match.

function searchForClearing() {

  var userInput = document.getElementById("clearingnummerTextBox").value;

  for (var i in testArray) {
    var currentObject = testArray[i];

    if (Array.isArray(currentObject.value)) {

      for (i = 0; i < currentObject.value.length; i++) {

        if (currentObject.value[i].length === 9) {

          var firstInterval = currentObject.value[i].split('-')[0];

          var lastInterval = currentObject.value[i].split('-')[1];

          if (userInput >= firstInterval && userInput <= lastInterval) {
            console.log("Inmatat: " + userInput + " " + "Träff på: " + currentObject.value);
            document.getElementById("bankResult").innerHTML = currentObject.label;
            console.log("Sökte mellan intervallen: " + firstInterval + " - " + lastInterval);

            console.log("9 teckens sök");
          }

        } else if (currentObject.value[i].length === 6) {

          if (userInput == currentObject.value[i]) {
            console.log("Inmatat: " + userInput + " " + "Träff på: " + currentObject.value);
            document.getElementById("bankResult").innerHTML = currentObject.label;
            console.log("Sökte mellan intervallen: " + firstInterval + " - " + lastInterval);
            console.log("6 teckens sök");
          }
        }
      }
    } else {
      if (currentObject.value.length === 9) {

        var firstInterval = currentObject.value.split('-')[0];
        var lastInterval = currentObject.value.split('-')[1];

        if (userInput >= firstInterval && userInput <= lastInterval) {
          console.log("Inmatat: " + userInput + " " + "Träff på: " + currentObject.label);
          document.getElementById("bankResult").innerHTML = currentObject.label;
          console.log("Sökte mellan intervallen: " + firstInterval + " - " + lastInterval);
          return true;
        }

      } else if (currentObject.value.length === 4) {

        if (userInput == currentObject.value) {
          console.log("Träff på clearingnummer som inte var i en array: " + userInput + " " + currentObject.label);
          document.getElementById("bankResult").innerHTML = currentObject.label;
          return true;
        }

      }

    }
  }
}

推荐答案

"39999"之所以会返回true的原因是,尽管它超出范围是因为比较了JS中的字符串

The reason you have "39999" return true even though its out-of-range is because strings in JS are compared lexographically.

"39999" < "4999" // true
 39999  <  4999  // false

您需要使用

You need to converted the strings to numbers using something like parseInt before doing the comparison.

就减少一些嵌套的if混乱而言,此示例的两个最好的朋友是

As far as reducing some of the nested if mess, your two best friends for this example are Array.prototype.find and Array.prototype.some.

findsome都遍历一个数组,为每个元素调用一个函数.

Both find and some iterate over an array calling a function for every element.

  • find:如果该函数返回true,则find停止迭代并返回当前元素.您可以使用它在testArray中找到一个对象,该对象的value等于用户输入或包含在一个范围内.

  • find: If that function returns true, find stops iterating and returns the current element. You can use it to find an object within your testArray whose value is equal to the user input or contains it in a range.

some:如果该函数返回true,则some停止迭代并返回true.当testArray值是一个数组时,可以使用它来检查用户输入是否在至少一个范围内.我们使用some而不是另一个find是因为我们只想检查数组中是否包含某些内容,而我们实际上并不希望将其取回.

some: If that function returns true, some stops iterating and returns true as well. You can use it when the testArray value is an array to check if user input is within at least one of the ranges. We use some instead of another find because we only want to check if something is contained in an array and we don't care to actually get it back.

这是使用findsome编写函数的方式:

Here's how you can write your function using find and some:

function findTestObject(input) {

  // iterate over the test array and 
  // stop as soon we found a match 
  // (as the passed function returns true)
  return testArray.find(function (testObj) {
    var value = testObj.value;

    // if current value is an array of ranges
    // check if userInput is within at least one of the ranges
    if (Array.isArray(value)) {
      return value.some(function (range) {
        // split the current range into min and max and compare with user input
        var rangeData = range.split('-');
        return parseInt(rangeData[0]) <= input && input <= parseInt(rangeData[1]);
      });
    } 
    // otherwise do a direct comparison
    else {
      return value === input;
    }
  });
}

此函数将从testArray返回其值与用户输入匹配的第一个对象,或者返回undefined.

This function will either return the first object from testArray whose value matches user input, or undefined.

这是一个完整的例子:

var testArray = [{
  "label": "Nordea",
  "value": ["1100-1199", "1400-2099", "3000-3399", "3410-4999"]
}, {
  "label": "Swedbank",
  "value": ["7000-7120", "7123-8104", "8106-8999"]
}, {
  "label": "Sparbanken Nord",
  "value": "8264"
}, {
  "label": "Sparbanken i Enköping",
  "value": ["7121-7122", "8305-5"]
}];

function findTestObject(input) {
  return testArray.find(function (testObj) {
    var value = testObj.value;

    if (Array.isArray(value)) {
      return value.some(function (range) {
        var rangeData = range.split('-');
        return parseInt(rangeData[0]) <= input && input <= parseInt(rangeData[1]);
      });
    } else {
      return value === input;
    }
  });
}

function test() {
  var userInput = document.getElementById("input").value;
  var result = findTestObject(userInput);
  var label = result ? result.label : 'Not Found';
  document.getElementById("result").innerHTML = label;
}

<input id="input" placeholder="Enter something..."/>
<button onclick="test()">Test</button>
<br />
Result: <div id="result"></div>

注意:您的示例中存在不一致之处.除了最后一个数组中的"8305-5"以外,所有范围都按升序排列(最小,最大). 使用上面的代码,此范围将永远不会返回true.

Note: You have an inconsistency in your example. All the ranges are in increasing order (min, max) except in the last array, where you have "8305-5". With the code above, this range will never return true.

解决此问题的一种方法是在比较之前始终对范围数组进行升序排序.

One way you can solve this is to always sort the range array in ascending order before comparing.

var rangeData = range.split('-').sort();

请参见如何正确对整数数组进行排序例子和陷阱.

这篇关于检查输入是否在两个值之间(多个条件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆