新随笔  :: 联系 :: 订阅 订阅  :: 管理

javascript秘籍

Posted on 2011-08-18 23:25  张贺  阅读(208)  评论(0编辑  收藏  举报

1、Global variables
Did you know that all global variables are also properties of the window object? They are! What does this mean? Well, it means that we can create global variables from inside a function. In fact, let's make a function that exists JUST to create new global variables

Code:
function makeNewGlobal( varName, val )
 {
 	window[varName] = val;
 }
 
 makeNewGlobal( "greeting", "Hello World!" );
 alert( greeting ); // Alerts 'Hello World!'
2、The parseInt() function
A very handy function indeed, but what happens here?
Code:
var myString = "010";
 var myNum = parseInt( myString );
Does myNum now equal 10? Noooo. myNum is now equal to 8. Why? Becase parsenInt does it's best to guess the proper radix based on the input (8, 10, or 16), and a number like 010 looks octal. It's the leading zero in the string that trips up parseInt() here. It is not very well known that parseInt can take a second parameter. You guessed it, the radix.
Code:
var myString = "010";
 var myNum = parseInt( myString, 10 );
This gives us what we expect, myNum is now equal to 10.