《Javascript秘密花园》学习笔记(终)

来源:互联网 发布:2015年总决赛库里数据 编辑:程序博客网 时间:2024/04/29 21:58

实践了许多代码后,回头再看《Javascript秘密花园》,又有一些收获,与诸君分享

数组

typeof运算符

Value               Class      Type-------------------------------------"foo"               String     stringnew String("foo")   String     object1.2                 Number     numbernew Number(1.2)     Number     objecttrue                Boolean    booleannew Boolean(true)   Boolean    objectnew Date()          Date       objectnew Error()         Error      object[1,2,3]             Array      objectnew Array(1, 2, 3)  Array      objectnew Function("")    Function   function/abc/g              RegExp     object (function in Nitro/V8)new RegExp("meow")  RegExp     object (function in Nitro/V8){}                  Object     objectnew Object()        Object     object

可以看出,typeof运算符主要有这些值:object,string,number,function.使用new关键字创建的对象除去function外typeof运算符都会得到object.但在判断string和number之间很好用,尤其是数组中的元素是否为string或number

//给出一个数组var test = [1,'1',true,new Function(""),'asd',function(){}];typeof test[0]//numbertypeof test[1]//stringtypeof test[2]//booleantypeof test[3]//functiontypeof test[4]//stringtypeof test[5]//function

由上段代码可以看出typeof运算符在对非new关键字创建的元素类型【尤其是数组元素类型】判断上很好用。注意1和‘1’的判断。
所以要判断数组中的元素是否为数值类型(Number),可以这样写:

var test = [12,'123',123,'2222','agc'];for(var i=0,len=test.length;i<len;i++){    console.log(typeof test[i])}
0 0
原创粉丝点击