简体   繁体   English

为什么这个假条件返回真?

[英]Why this false condition returns true?

Why when i write on the last input 6 instead of 60 and click ob the button, it returns to true thought my condition is false?为什么当我在最后一个输入 6 而不是 60 上写并单击 ob 按钮时,它返回 true 认为我的条件为 false? How to solve this problem?如何解决这个问题呢? Thanks in advance!提前致谢!

<!doctype html>
<html>

  <head>
  </head>

  <body>
    <button>get
      result</button>
    <div></div>
    <input Class="value1" value=10>
    <br>
    <br>
    <input Class="value2" value=20>
    <br>
    <br>
    <input Class="value3" value=30>
    <br>
    <br>
    <input Class="value4" value=40>
    <br>
    <br>
    <input Class="value5" value=50>
    <br>
    <br>
    <input Class="value6" value=60>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
      $('button').click(function() {
        var value1 = $(".value1").val();
        var value2 = $(".value2").val();
        var value3 = $(".value3").val();
        var value4 = $(".value4").val();
        var value5 = $(".value5").val();
        var value6 = $(".value6").val();

        if (value1 < value2 && value2 < value3 && value3 < value4 && value4 < value5 && value5 < value6) {

          $("div").text("true");
        } else {

          $("div").text("false");
        }

      });

    </script>
  </body>

</html>

A simple solution to your issue is convert the input box to be of type "Number", to limit the characters inputted, then convert all variables to Number.您的问题的一个简单解决方案是将输入框转换为“数字”类型,以限制输入的字符,然后将所有变量转换为数字。

For example:例如:

<input  Class="value3" type="number" value=30>

$('button').click(function() {
    var value1 = Number($(".value1").val());
    var value2 = Number($(".value2").val());
    var value3 = Number($(".value3").val());
    var value4 = Number($(".value4").val());
    var value5 = Number($(".value5").val());
    var value6 = Number($(".value6").val());
});

You are comparing strings (from.value), not numbers.您正在比较字符串(from.value),而不是数字。


You could utilise a loop with the converted values with unary plus + , like您可以使用带有一元加+转换值的循环,例如

let isIncreasing = true
let i = 1
while (i < 6 && isIncreasing) {
    isIncreasing = +$(".value" + i).val() < +$(".value" + (++i)).val();
}

if (isIncreasing) $("div").text("true");
else $("div").text("false");

By default your input value is numeric (input=30), but when you change value in your input, that become string value, and there are not implicit converstion of string to numeric.默认情况下,您的输入值为数字(输入 = 30),但是当您更改输入中的值时,该值将变为字符串值,并且不会将字符串隐式转换为数字。

When you get numeric value of input, use parse function like Number or parseInt当你得到输入的数值时,使用 parse function like Number 或 parseInt

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

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