什么时候应该在if语句的条件中使用括号? [英] When should you use parentheses inside an if statement's condition?

查看:317
本文介绍了什么时候应该在if语句的条件中使用括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的if条件:

$(document).ready(function(){
  var name = 'Stack';
  var lastname = 'Overflow';
   if( name == 'Stack' && lastname == 'Overflow' )
   alert('Hi Stacker!');
});

所以我的警告被解雇了......

So my alert is fired...

如果我把条件放在这样的括号内:

If I put my condition inside a brackets like this:

 $(document).ready(function(){
  var name = 'Stack';
  var lastname = 'Overflow';
   if( (name == 'Stack') && (lastname == 'Overflow') ){
      alert('Hi Stacker!');
   } 
});

我的提醒也被解雇了......

My alert is also fired...

我的问题是:何时以及为什么我应该在if条件中使用括号?谢谢!

My question is: When and why I should use parentheses inside my if condition? Thank you!

推荐答案

如果需要检查多个条件,可以使用括号。

Brackets can be used, if multiple conditions needs to be checked.

例如:如果全名为StackOverflow,则用户也是堆栈器,然后使用或运算符添加另一个条件。

For ex: User is also a Stacker if full name is 'StackOverflow' then add another condition with 'Or' operator.

if(((name == 'Stack') && (lastname == 'Overflow')) || FullName =='StackOverflow')

如您所见,名称和姓氏放在一个括号内意味着它给出一个结果为true或false,然后它使用FullName条件进行OR运算。

As you can see, name and last name are placed inside one bracket meaning that it gives a result either true or false and then it does OR operation with FullName condition.

并且在名称,姓氏和全名字段周围括号是可选的,因为它不是对条件没有任何影响。但是,如果您使用FullName检查其他条件,则将它们分组到括号中。

And having brackets around name, lastname and fullname fields are optional since it doesn't make any difference to the condition. But if you are checking other condition with FullName then group them into bracket.

这篇关于什么时候应该在if语句的条件中使用括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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