# 章序号/节序号/节/笔记序号 codecademy, Condition # 概念阐释 - 运用于**同时满足2个变量**的情况。 - 运用条件就不得不用到==布尔值==,**逻辑运算符**是js里与布尔值一起运用的。 - 我们可以使用逻辑运算符来增加复杂的逻辑 - 逻辑运算符可以比较多组[[js condition Comparison Operators 比较操作符]]的结果。 - **逻辑运算符既可以在两组变量与变量之间,也可以在变量与要比较的结果之间。** ## 语法 ![](http://image.harryrou.wiki/2023-01-11-%E6%88%AA%E5%B1%8F2023-01-11%2008.29.37.png) ![](http://image.harryrou.wiki/2023-01-11-%E6%88%AA%E5%B1%8F2023-01-11%2008.31.23.png) # 举例子 ### 使用&&运算符 ![](http://image.harryrou.wiki/2023-01-11-%E6%88%AA%E5%B1%8F2023-01-11%2008.37.32.png) - 两个条件都**必须为true**,整个条件才为true,`if`块执行 - 否则`else`块执行 ### 使用||运算符 ![](http://image.harryrou.wiki/2023-01-11-%E6%88%AA%E5%B1%8F2023-01-11%2008.43.13.png) - 两个条件**至少满足一个true**,结果就为true,`if`块执行 - 一个都不满足,`else`块执行 - 今天是周六或者周日,结果为enjoy the weekend - 今天是不是周六或周日,结果为 do some work ### 使用!运算符 ![](http://image.harryrou.wiki/2023-01-11-%E6%88%AA%E5%B1%8F2023-01-11%2008.43.42.png) - 返回**相反**的结果 - !excited = !true 结果为false - !sleep = !false,结果为true - 注意:不要和`!==` 的比较运算符混淆 # 类比、比较与对比 - 2个以上变量组合使用 - [[js condition short-circuit 短路值]] - 1个变量,多个条件 - [[js condition switch 语句]] - [[js condition Else If 语句]] - 1个变量,真假条件 - [[js condition if else语句]] - [[js condition Ternary Operator 三元运算符]] # 问题 **1.** 写出这些条件的结果? ![](http://image.harryrou.wiki/2023-01-11-%E6%88%AA%E5%B1%8F2023-01-11%2008.57.06.png) **2.** In **main.js** there are two variables `mood` and `tirednessLevel`. Let’s create an `if...else` statement that checks if `mood` is `'sleepy'` and `tirednessLevel` is greater than `8`. If both conditions evaluate to `true`, then `console.log()` the string `'time to sleep'`. Otherwise, we should `console.log()` `'not bed time yet'`. After you press “Run”, play around with the `||` operator and the `!` operator! What happens if you negate the value of the entire statement with `!` and switch to `||` instead of `&&`? ```js let mood = 'sleepy'; let tirednessLevel = 6; ``` **3.** 尝试不同逻辑条件的结果? - 当心情为sleepy并且疲劳阈值为6时? - 当心情或疲劳阈值有一个为true时? - 当使用!时,什么时候会得出true的结果? # 问题答案 **1.** ![](http://image.harryrou.wiki/2023-01-11-%E6%88%AA%E5%B1%8F2023-01-11%2008.57.06%202.png) **3.** ```js if (mood !=='not sleepy' && tirednessLevel !== 8){ console.log('time to sleep'); } else{ console.log('not bed time yet'); } // 比较运算符的写法 ``` # 备注(经验集/错误集) - 自己设定的真实小场景更容易让概念与实际运用结合起来。 - *let后面的变量是一个初始设定值* - *if里的真值是条件,“如果阈值大于等于6了就需要休息了,这和下班时间一个意思,我需要在5点及以后的时间都现实下班,所以都可以用>=”* - *真正发生改变的是重新设定变量的值,可以把阈值设定为8或者4** *错误:没有用对比较运算符*