If conditions false then prevent default

后端 未结 2 1490
轮回少年
轮回少年 2021-01-17 16:09

I have a link. When some one clicks on that I want to check some conditions before letting it work. If it\'s false the default action should be prevented.

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 16:55

    Be careful:

    !a evaluates to true or false. If a conversion of a to a bool is true then !a evaluates to false.

    All positive integers evaluate to true. So !a will evaluate to false. A comparison using double equals == to 1 will test that boolean !a with the boolean 1 or true. So if a is a positive integer as I suspect it is then your if statement will ALWAYS evaluate to false.

    If you want to test is something is NOT something else you need to change the first equals in your comparison operator (===) to be a !.

    E.g. var a = 2; if(a!==1) { // do something } <-- A is 2 and therefore the if comparison wille evaluate to true as a does not equal 1.

    In your code we have:

    var a = 2;
    if(!a==1){
      // a was 2 (or boolean true by default)
      // but using ! has negated its boolean value
      // so !a evaluates to boolean false
      // which is being compared to 1 (evaluating to boolean true)
      // so this if statement will never get here
    }
    

    Hope that helps

    P.S. Remember your comparison operators:

    !"hello world" == 0 // true
    !"hello world" === 0 // false
    

    Update

    I saw your comment on another post which said that a is 0 until something happens then it is 1.

    In this case:

    var a = 0; // integer 0 or bool false
    if(!a==1){ // if the bool opposite of 0 (false) is equal to 1 (true)
      // well, opposite of false is true, so you're checking if true is equal to true
      // so this will get called
      e.preventDefault();
    }
    

提交回复
热议问题