您的位置:首页 > Web前端 > JavaScript

php程序员学习javascript:第一章:javascript基本语法:数据类型

2012-11-26 13:00 896 查看
一、变量声明及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(); //其他定义对象的方向会在后续章节中介绍

例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript基本语法</title>
<script type="text/javascript">
//javascript中用var关键词来定义一个变量,而php中直接,用$变量名即可定义一个变量
var message;
//javascript中的数据类型:undefined,string,number,boolean,object,function
//php的数据类型:         string,float,int,bool,resource,object,array,null
//javascript中判断一个变量的数据类型用typeof(变量名)
//php中用is_float(),is_int(),is_bool(),is_string()
//alert(typeof(message));      //输出undefined 未赋值的变量
//alert(typeof(hello));       //输出undefined 未定义的变量
//alert(hello);               //因为hello这个变量未被声明,所以会出现语法错误:ReferenceError: hello is not defined :alert(hello);
var test = undefined;
//alert(typeof(test));         //输出undefined
//alert(test);                   //输出undefined
var nullVar = null;
//alert(typeof(nullVar));          //输出object
//alert(nullVar);                   //输出null
var boolVar = true;
//alert(typeof(boolVar));           //输出boolean
var intVar = 1;
//alert(typeof(intVar));              //输出number
//alert(Boolean(intVar));               //输出true

var floatStr = '1.32';
//alert(Number(floatStr));            //输出1.32
var notN = 'str';
//alert(isNaN(floatStr));               //false
//alert(isNaN(notN));                     //true
//document.write(parseInt(floatStr,10));        //输出1
var intStr = '125';
document.write(parseFloat(intStr));             //输出125
</script>
</head>

<body>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: