php程序员学习javascript:第一章:javascript基本语法:数据类型
一、变量声明及javascript数据类型概述:
(1)变量声明
javascript中使用关键词var来声明一个变量:如var message;
注:php中使用$来声明一个变量:$name;
(2)数据类型
javascript中的数据类型: undefined, string, number, boolean,null, object, array,function
注:php中的数据类型: string,int,float,boolean,null,resource,array,object
通过typeof(变量名)函数可以查看一个变量的数据类型
注:php中通过is_string,is_int,is_float等来判断一个变量的数据类型
二、数据类型详解
1、undefined
它是一个特殊的值,当一个变量未赋值时,它的默认值就是undefined
当一个变量未声明时,用typeof函数,它也是undefined类型,但直接使用这个未声明的变量会出现语法错误
2、null
它也是一个特殊的值,代表一个空对象指针
用typof检测它的数据类型时,是object,因为它是一个空对象指针
3、boolean
它只有两个值:true和false
这两个值与数字值不是一回事,因此true不一定等于1,false不一定等于0
可以通过Boolean来将一个变量转化为一个boolean型
4、Number
它可以分为:int、float、NaN
NaN是一个特殊的值,代表一个变量不是数值型,可以通过isNaN来检测一个变量是否为NaN
通过Number可以将一个变量转化为一个数值型
为了更加准确,建议使用parseInt()和parseFloat()来转化
5、String
在javascript中双引号和单引号意义是一样的
字符串,都有length这个属性和toString()的方法
var lang = 'zh-cn';
document.write(lang.length);
var age = 26;
document.write(lang.toString());
6、Object
对象类型
定义一个对象:var obj = new Object(); //其他定义对象的方向会在后续章节中介绍
例子:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>Javascript基本语法</title> 6 <script type="text/javascript"> 7 //javascript中用var关键词来定义一个变量,而php中直接,用$变量名即可定义一个变量 8 var message; 9 //javascript中的数据类型:undefined,string,number,boolean,object,function 10 //php的数据类型: string,float,int,bool,resource,object,array,null 11 //javascript中判断一个变量的数据类型用typeof(变量名) 12 //php中用is_float(),is_int(),is_bool(),is_string() 13 //alert(typeof(message)); //输出undefined 未赋值的变量 14 //alert(typeof(hello)); //输出undefined 未定义的变量 15 //alert(hello); //因为hello这个变量未被声明,所以会出现语法错误:ReferenceError: hello is not defined :alert(hello); 16 var test = undefined; 17 //alert(typeof(test)); //输出undefined 18 //alert(test); //输出undefined 19 var nullVar = null; 20 //alert(typeof(nullVar)); //输出object 21 //alert(nullVar); //输出null 22 var boolVar = true; 23 //alert(typeof(boolVar)); //输出boolean 24 var intVar = 1; 25 //alert(typeof(intVar)); //输出number 26 //alert(Boolean(intVar)); //输出true 27 28 var floatStr = '1.32'; 29 //alert(Number(floatStr)); //输出1.32 30 var notN = 'str'; 31 //alert(isNaN(floatStr)); //false 32 //alert(isNaN(notN)); //true 33 //document.write(parseInt(floatStr,10)); //输出1 34 var intStr = '125'; 35 document.write(parseFloat(intStr)); //输出125 36 </script> 37 </head> 38 39 <body> 40 </body> 41 </html>