偶然间碰到了一个很有意思的Javascript,alert(1&&2)输出的是什么,小伙伴,你知道吗?
答案是2,哈,对了没有,为什么呢……下面鄙人来简单讲讲吧。
我们先来测试数据,比较有代表性的,先看alert(A && B),
alert(1 && 0) //output 0
alert(0 && 1) //output 0
alert(' ' && 0) //output
alert(0 && ' ') //output 0
alert(' ' && 'a') //output
alert('a' && ' ') //output
发现规律了没有,在计算机语言中,我们可以这么看,‘ ’跟0相当于false,那么有数值的1,2,‘a'就相当于true,我们可以发现这么个规律:
在 alert(A && B) 中,当A为true时,返回的均是B;当A为false时,返回的均为A。
同理,在alert(A || B)中,取数据测试“
alert(1 || 0) //output 1
alert(0 || 1) //output 1
alert(' ' || 0) //output 0
alert(0 || ' ') //output 0
alert(' ' || 'a') //output a
alert('a' || ' ') //output a
在 alert(A || B) 中,当A为true时,返回的均是A;当A为false时,返回的均为B。
我么发现:
alert(true && false) //output false
alert(true && true) //output true(第2个)
alert(false && true) //output false
alert(false && false) //output false(第1个)
alert(true || false) //output true
alert(true || true) //output true(第1个)
alert(false || false) //output false(第2个)
alert(false || true) //output true
可以这么记,A&&B“第一选择”不是true;A||B“第一选择”不是false。
同时 && 的优先级高于 ||,如alert('a' || '' && 2),返回 a;如果 || 的优先级高于 && ,则返回的是 2。
聪明的小伙伴,你发现了吗?