javascript基础学习(一)

怀着测试的态度学习!

一、Javascript的变量类型

 1 function debug(e){
 2     if(!document.all){
 3         console.log(e);
 4     }else{
 5         document.writeln(e);
 6     }
 7 }
 8 var a = 1; //echo number
 9 var b = '1'; //echo string
10 var c = true; //echo boolean
11 var d = null; //echo object 注:null是空对象
12 var e = undefined; //echo undefined
13 var f = new Object(); //echo object
14 var g = new Array(); //echo object 注: array 继承object
15 var h = function(){ }//echo function
16         
17 debug(typeof a);
18 debug(typeof b);
20 debug(typeof c);
21 debug(typeof d);
22 debug(typeof e);
23 debug(typeof f);
24 debug(typeof g);
25 debug(typeof h);

变量的类型有number、string、boolean、object、function、undefined这几种类型。其中null为空对象,array也是object类型,只不过是继承自object,通过typeof可以查看它们的类型。object、array都是赋值引用。

二、变量之间的等值比较

 1     var a = 1;
 2     var b = 1;
 3     debug(a == b); //true
 4     debug(a + b); //2
 5     var a = new Number(1); //是对象
 6     var b = new Number(1); //是对象
 7     debug(a == b); //false
 8     debug(a + b); //2
 9     var a = new Object();
10     var b = new Object();
11     debug(a == b); //false
12     var a = new Array();
13     var b = new Array();
14     debug(a == b); //false

三、基础类型判断函数

 1     /**
 2      * 判断变量是否为对象
 3      */
 4     function is_object(o){
 5         return (typeof o === 'object');
 6     }
 7     /**
 8      * 判断变量是否为数组
 9      */
10     function is_array(a){
11         return ((typeof a === 'object') && (a instanceof Array));
12         //不能单独以constructor来判断此对象是否为Array对象,可能继承自Array
13         //return ((typeof arr === 'object') && arr.constructor === Array);
14     }   
15     /**
16      * 判断是否为字符串
17      */
18     function is_string(s){
19         return (typeof s === 'string');
20     }
21 
22     /**
23      * 判断是否为数字
24      */
25     function is_number(n){
26         force = false || arguments[1];
27         if(force){
28             return (typeof n === 'number');
29         }else{
30             return (typeof n === 'number') || (is_string(n) && n.replace(/^\d+$/, '') == '');
31         }
32     }
33     /**
34      * 是否为函数
35      */
36     function is_function(f){
37         return (typeof f === 'function');
38     }

四、克隆对象

 1     /**
 2      * 克隆对象
 3      */
 4     function clone(o){
 5         if(!is_object(o)){
 6             return null;
 7         }
 8         var t = new Object();
 9         for(i in o){
10             if(is_object(o[i])){
11                 t[i] = clone(o[i]);
12             }else{
13                 t[i] = o[i];
14             }
15         }
16         return t;
17     }

 

posted @ 2012-12-07 22:22  Red Candle  阅读(175)  评论(0编辑  收藏  举报