面试笔试题总是有类似的题目,真的十分的烦人,写个文章记录一下
来让我们循序渐进......
首先我们要知道:
在js逻辑运算中,0、”“、null、false、undefined、NaN都会判为false,其他都为true
1、&&
先给个大家都知道的结论:
只有前后都为 true 时才返回 true,否则返回 false
这句话是正确的,但是实际遇到的不会是十分单调的 true or false,接下来就列举各种情况:
console.log(0 && '') // 0
0 转译为 false,'' 转译为 false,输出 0
console.log('' && 0) // ''
'' 转译为 false,0 转译为 false,输出 ''
console.log(1 && 'a') // 'a'
1 转译为 true,'a' 转译为 true,输出 'a'
console.log('a' && 1) // 1
'a' 转译为 true,1 转译为 true,输出 1
console.log(0 && 1) // 0
0 转译为 false,1 转译为 true,输出 0
console.log(1 && 0) // 0
1 转译为 true,0 转译为 false,输出 0
结论
只要 ' && ' 前面是 false,无论 ' && ' 后面是 true 还是 false,结果都将返 ' && ' 前面的
值;
只要 ' && ' 前面是 true,无论 ' && ' 后面是 true 还是 false,结果都将返 ' && ' 后面的
值;
2、||
同样先上个大家都知道的结论:
只有前后都是false的时候才返回false,否则返回true
列举各种情况:
console.log(0 || '') // ''
0 转译为 false,'' 转译为 false,输出 ''
console.log('' || 0) // ''
'' 转译为 false,0 转译为 false,输出 0
console.log(1 || 'a') // 1
1 转译为 true,'a' 转译为 true,输出 1
console.log('a' || 1) // 'a'
'a' 转译为 true,1 转译为 true,输出 'a'
console.log(0 || 1) // 1
0 转译为 false,1 转译为 true,输出 1
console.log(1 || 0) // 1
1 转译为 true,0 转译为 false,输出 1
结论
只要 ' || ' 前面为 false,不管 ' || ' 后面是 true 还是 false,都返回 ' || ' 后面的
值。
只要 ' || '前面为 true,不管 ' || ' 后面是 true 还是 false,都返回 ' || ' 前面的
值。
最最最后,我们回到题目里出的问题:
console.log(1 && 2) // ?
1 转译为 true,2 转译为 true,所以输出 2,没毛病。