刘作权博客
火华
JS pitfalls: null, false, undefined, NaN
2014-09-05 16:00:00   阅读1111次

Comparison operators

Comparison via ==

Equality, regardless of type.

Comparison via ===

Identity, types must match. Always use this syntax, if possible.

Pitfalls using comparison

0

Evaluates to false in boolean operations. Always use === when comparing to the number 0.

var x = 0;
var y = false;

x == y → truex === y → false

"" (empty string)

Evaluates to false in boolean operations. Always use === when comparing to an empty string.

var x = "";
var y = false;

x == y → truex === y → false

null

Evaluates to false in boolean operations. Always use === when comparing to null.

var x = null;
var y = false;

x == y → truex === y → false

undefined

If a variable hasn't been declared or assigned yet (an argument to a function which never received a value, an object property that hasn't been assigned a value) then that variable will be given a special undefined value.

Evaluates to false in boolean operations. Always use === when comparing to undefined.

var x;
var y = false;

typeof(x) → undefined (as a string)

x == y → truex === y → false

NaN

Not a Number, generated when arithmetic operations return invalid results.

Evaluates to false in boolean operations. Always use isNaN() when comparing to NaN.

var x = 10/seventeen;

x → NaN

NOTE: NaN is never equal to itself!

var x = 10/seventeen;

x == x → false

Source

see http://www.hunlock.com/blogs/Essential_Javascript_--_A_Javascript_Tutorial

In general a very good and interesting site, yet some of their examples contradict to my judgment of good code, so beware.




-----------------------------------------------------
转载请注明来源此处
原地址:#

-----网友评论----
暂无评论
-----发表评论----
微网聚博客乐园 ©2014 blog.mn886.net 鲁ICP备14012923号   网站导航