2012年7月10日 星期二

=== vs ==


The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. It's this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.
To quote Douglas Crockford's excellent JavaScript: The Good Parts,
JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
'' == '0'           // false
0 == ''             // true
0 == '0'            // true
false == 'false'    // false
false == '0'        // true
false == undefined  // false
false == null       // false
null == undefined   // true
' \t\r\n ' == 0     // true
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and!==. All of the comparisons just shown produce false with the === operator.
Reference:
  http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use

typeof function

typeof(para)  會回傳 para 的型別
可能的回傳值有 "number"、"string"、"boolean"、"object"、"function" 和 "undefined"
以下是例子

document.writeln(typeof(1)); // number
document.writeln(typeof("str")); // string
document.writeln(typeof(true)); // boolean
document.writeln(typeof({})); // object
document.writeln(typeof([])); // object
document.writeln(typeof(function(){})); // function


document.writeln(typeof(new Number(1))); // object
document.writeln(typeof(new String("str"))); // object
document.writeln(typeof(new Boolean(true))); // object
document.writeln(typeof(new Object())); // object
document.writeln(typeof(new Array())); // object
document.writeln(typeof(new Function())); // function


document.writeln(1 == new Number(1)); // true
document.writeln("str" == new String("str")); // true
document.writeln(true == new Boolean(true)); // true


document.writeln(typeof(new Number(1) + 0)); // number
document.writeln(typeof(new Number(1).valueOf())); // number
document.writeln(typeof(new String("str").valueOf())); // string
document.writeln(typeof(new Boolean(true).valueOf())); // boolean


Reference: