当前位置: 首页> 教育> 锐评 > 了解逻辑中断

了解逻辑中断

时间:2025/8/27 1:29:17来源:https://blog.csdn.net/m0_58258716/article/details/140496172 浏览次数:0次

1. 逻辑运算符里的短路

  • 短路:只存在于&&和||中,当满足一定条件会让右边代码不执行

符号短路条件
&&左边为false就短路
||左边为true就短路
console.log(11 && 22)    // 输出结果是22
console.log(11 || 22)   // 输出结果是11
console.log(0 && 22)   // 输出结果是0
console.log(false || 22)   // 输出结果是22
  • 原因:通过左边能得到整个式子的结果,因此没必要再判断右边

  • 运算结果:无论&&还是||,运算结果都是最后被执行的表达式,一般用在变量赋值

2. 转换为Boolean型

2.1 显示转换:

  • Boolean(内容)

  • 记忆:''、0、undefined、null、false、NaN转换为布尔值后都是false,其余则为true。

console.log(false && 20) //false
console.log(5<3 && 20) // false
console.log(undefined && 20) //undefined
console.log(null && 20) //null
console.log(0 && 20) // 0
console.log(10 && 20) // 20
​
console.log(false || 20) // 20
console.log(5<3 || 20) // 20
console.log(undefined || 20) // 20
console.log(null || 20) // 20
console.log(0 || 20) // 20
console.log(10 || 20) // 10

2.2 隐式转换:

  • 有字符串的加法""+1,结果是“1”

  • 减法-(想大多数数学运算符一样)只能用于数字,它会使空字符""转换成0

  • null经过数字转换之后会变为0

  • undefined经过数字转换之后会变为NaN

console.log(''-1) // -1
console.log('hello'-1) // NaN
console.log(null + 1) // 1
console.log(undefined + 1)// NaN
console.log(NaN + 1) // NaN
关键字:了解逻辑中断

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: