这期的问题是

// 请问如下 alert 语句依次弹出的是什么?
alert('' == '0'); 
alert('' == false); 
alert('0' == 0);
alert('\n' == 0); 
alert(null == false); 
alert(null == undefined); 

此道题目的解释可以参考 《PPK on Javascript》 上的解释 -- form 玉伯:

These are the rules for converting other data types to booleans:

The values null and undefined become false.
The numbers 0 and NaN become false.
An empty string '' becomes false.
All other values become true.

在这里需要注意的是这句

An empty string '' becomes false. 

「empty string」 的含义包括不可见字符(\"\n \t \v\" 等),所以极端上考虑 alert(\"\n \t \v\" == 0) 这个也是 true 。

此道题目的最后答案是 false、true、true、true、false、true 。因此,「在不明确强制类型转换(或者要求判断结果比较高)时,尽量使用 === 替代 == 」 -- form 小马 。

-- Split --

另,外加一道 玉伯 的题目:

var testObj = {
    alert: function() { alert('2'); },
    init: function(el) {
        YAHOO.util.Event.on(el, 'click', function() {
            this.alert('1'); // ?
            (function() { this.alert('1'); })(); // ?
            (function() { this.alert('3'); }).call(this); // ?
        }, null, this);
    }
};

testObj.init(document);
// 问题: 点击 document,alert 依次输出什么?

这道题目需要注意三点:

  1. YAHOO.util.Event.on(el, eventType, fn, obj, override) 最后两个参数的使用
  2. 匿名函数中,this === window
  3. call 和 apply 的使用

最后答案为 「2, 1, 2」,相关参考资料: