先观察以下PHP代码:
if ('' == false) echo 'OK'.PHP_EOL;
else echo 'NO'.PHP_EOL;if ('') echo 'OK'.PHP_EOL;else echo 'NO'.PHP_EOL;if ('0' == false) echo 'OK'.PHP_EOL;else echo 'NO'.PHP_EOL;if ('0') echo 'OK'.PHP_EOL;else echo 'NO'.PHP_EOL;if (array() == false) echo 'OK'.PHP_EOL;else echo 'NO'.PHP_EOL;if (array()) echo 'OK'.PHP_EOL;else echo 'NO'.PHP_EOL;if (array(0) == false) echo 'OK'.PHP_EOL;else echo 'NO'.PHP_EOL;if (array(0)) echo 'OK'.PHP_EOL;else echo 'NO'.PHP_EOL;在看以下Javascript代码:
if ('' == false) console.log('OK');else console.log('NO');if ('') console.log('OK');else console.log('NO');if ('0' == false) console.log('OK');else console.log('NO');if ('0') console.log('OK');else console.log('NO');if ([] == false) console.log('OK');else console.log('NO');if ([]) console.log('OK');else console.log('NO');if ([0] == false) console.log('OK');else console.log('NO');if ([0]) console.log('OK');else console.log('NO');
以上PHP代码的输出结果为:
OKNOOKNOOKNONOOK
以上Javascript代码的输出结果为:
OKNOOKOKOKOKOKOK
经过分析,我发现,PHP在判断某操作数是否为真时都会把该操作数和true作==比较,并且array(0)==true;Javascript在判断某操作数是否为真时不作==比较,而是按人们的正常逻辑思维去做处理。比如:我们认为字符串'0'里面是有字符的,不为空串,所以为真。再比如:大多数人认为是数组就为真,不管数组里面有没有元素。并且在Javascript里面array(0)==false。这说明在作类型转换时,PHP和Javascript的实现机制也是不一样的。还是Javascript人性化一点,既然字符串'0'经过类型转换可以转换为0,那么数组[0]经过类型转换也要转换成0,符合正常人的逻辑思维。至于PHP的array(0)==true,单独记忆一下吧。