The difference between the application of Javascript comparison operators == and ===

   In Javascript, both == and === are operators used to compare whether two values ​​are equal. The difference between them lies in the way of comparison and type check. == is a mandatory type conversion comparison, and === is a non-mandatory type conversion comparison. In Javascript applications, in order to avoid the risks brought by type conversion, the === operator is usually preferred, which is also a standard application writing method. The following uses a verification code Demo to explain the difference between the two.



   First test the comparison of ==



insert image description here



   Check the input 12345 and the preset 123456, and the result is failure.



insert image description here



   Enter 123456 and the preset 123456 to check again, and the result is that the verification is passed.

insert image description here



insert image description here



   It can be seen that when the == comparator is used, the result will automatically convert the input output String (string type) to Number (number type) to compare the data.



   Turn to use === to test and compare, and also input 123456 to compare, and the result verification fails.



insert image description here



   The output String type can be converted into Number type, and then data comparison can be performed. There are many methods, mainly using parseInt() and Number() methods.



   parseInt() method: The parse() method also explained in detail its application to Json serialization and deserialization in previous issues.



insert image description here



   Numbrt() method: It can also successfully convert String to Number type.



insert image description here



   Test code:


 <script>
      var system_code = 123456;
      // var verify_code = parseInt(prompt('请输入验证码'));
      var verify_code = Number(prompt('请输入验证码'));
      console.log('system_code的类型为:' , typeof system_code);
      console.log('verify_code的类型为:',  typeof verify_code);

     
     function check_code(){
    
    
      if (verify_code === system_code){
    
    
         console.log('验证成功');
       }else{
    
    
         console.log('验证失败,请重新输入');
       };
       var isConfirm = confirm('请确认');

     };

     check_code();

    </script>


   Test video:


Application area of ​​Javascript comparison operators == and ===

Guess you like

Origin blog.csdn.net/weixin_48591974/article/details/131004512