Always specify the second argument-parseint
ParseintConverts a string to an int number, the syntax is:
Parseint (STR, [Radix])
The second argument is optional, which specify the radix of the first argument.
If you omit Radix, following the rules:
-> If the string begins with '0x ', the radix is 16.
-> If the string begins with '0', the radix is 8.
-> Otherwise, the radix is 10.
Therefore, the following code will confuse somebody who don't know this rules:
Parseint ('08'); // 0 parseint ('08', 10); // 8
Delete an element from an array
Whether can we useDeleteKeyword to achieve this:
VaR arr = [1, 2, 3, 4, 5]; Delete arr [1]; arr; // [1, undefined, 3, 4, 5]
You can see,DeleteCan't really delete an item. The removed item is replace withUndefinedValue, the array'sLengthIs not supported CED.In fact,SpliceMethod existing in the array. prototype can be helpful:
VaR arr = [1, 2, 3, 4, 5]; arr. splice (1, 1); arr; // [1, 3, 4, 5]
Function as object
Function in Javascript is also object; therefore we can assign properties even functions to function.
See example below:
Function add () {return Add. Count ++;} Add. Count = 0; add (); // 0add (); // 1add (); // 2
We assignCountProperty to function to record how many times the function is called.
This can be done in a more elegant way:
Function add () {If (! Arguments. callee. count) {arguments. callee. count = 0;} return arguments. callee. count ++;} Add (); // 0add (); // 1add (); // 2
Arguments. calleeRefer to the function which is current running.
Find the max value in an array
There is an array contains all of number, how to find out the max value.
VaR arr = [2, 3, 45, 12, 8]; var max = arr [0]; for (var I in ARR) {If (ARR [I]> MAX) {max = arr [I] ;}} Max; // 45
This also works, but we all know there isMathObject in javascript:
Math. Max (2, 3, 45, 12, 8); // 45
Can this be helpful? Yes
VaR arr = [2, 3, 45, 12, 8]; math. Max. Apply (null, arr); // 45
AddConsole. LogSupport in IE
We often useConsole. LogTo debug Javascript in Firefox with firebug support.
But it will break down ie 'execution, because IE doesn' t hasConsoleObject, we can simple fix it like this:
If (typeof (console) ==='undefined') {window. console ={ log: function (MSG) {alert (MSG) ;}}}console. log ('debug info. ');