这期的问题是
// 请问如下 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 依次输出什么?
这道题目需要注意三点:
- YAHOO.util.Event.on(el, eventType, fn, obj, override) 最后两个参数的使用
- 匿名函数中,this === window
- call 和 apply 的使用
最后答案为 「2, 1, 2」,相关参考资料:
这几天在学JS,翻Nicholas的JS高级程序设计书的时候第一章有前面几天的问题答案,哈哈,真是感激这些技巧分享,给平淡的学习过程加了很多乐趣
抢好座位啦.