js数据类型详细

来源:互联网 发布:知乎成功的原因 编辑:程序博客网 时间:2024/04/30 08:18
1、js数据类型

Javascript中的数据类型可以分为基本数据类型和复合数据类型两种:

基础数据类型有5种:Undefined、Null、Boolean、Number和String。

复合数据类型包括:函数(Function)、数组(Array)、Object(对象)。

(1)基础数据类型

1、Undefined

Undefined类型只有一个值,即undefined,使用var声明变量,但是未初始化的,这个变量就是Undefined类型的,例子: 

alert(i == undefined);//true 

var i;与var i = undefined;这两句是等价的。 

包含Undefined值的变量和未定义的变量是不一样的。

2、Null

Null类型也只有一个值:null.null表示一个空对象的指针。

3、Boolean

Boolean类型只有两个字面量true和false。但是js中多有的变量都可以使用Boolean()函数转换成一个Boolean类型的值。

4、Number

Number类型:整数和浮点数。NaN:Not a Number。这个数值用于本来要返回一个数值,但是却未能放回一个数值的情况,以防止报错。 

例如:1/0 返回的就是NaN。NaN的特点:1、任何涉及NaN的操作都会返回NaN。2、NaN对任何值都不相等,包括自己NaN本身。 针对NaN特性,JS内置了isNaN()函数,来确定数值是不是NaN类型。

5、String

字符串类型,字符串类型是最熟悉不过的啦,至于用单引号,还是双引号,在js中还是没有差别的。记得成对出现

(2)复合数据类型

1、函数(Function

<span style="white-space:pre"></span><script type="text/javascript"><span style="white-space:pre"></span>document.write(isFunction(function test(){}),'<br/>');<span style="white-space:pre"></span>document.write(isFunction(10),'<br/>');<span style="white-space:pre"></span>function isFunction(obj){<span style="white-space:pre"></span>return (typeof obj=='function')&&obj.constructor==Function;<span style="white-space:pre"></span>}<span style="white-space:pre"></span></script>

2、数组(Array

<span style="white-space:pre"></span><script type="text/javascript"><span style="white-space:pre"></span>var a=[0];<span style="white-space:pre"></span>document.write(isArray(a),'<br/>');<span style="white-space:pre"></span>function isArray(obj){<span style="white-space:pre"></span>return (typeof obj=='object')&&obj.constructor==Array;<span style="white-space:pre"></span>}<span style="white-space:pre"></span></script>

3、Object(对象)

<span style="white-space:pre"></span><script type="text/javascript"><span style="white-space:pre"></span>document.write(isObject(new Object()),'<br/>');<span style="white-space:pre"></span>document.write(isObject(10),'<br/>');<span style="white-space:pre"></span>function isObject(obj){<span style="white-space:pre"></span>return (typeof obj=='object')&&obj.constructor==Object;<span style="white-space:pre"></span>}<span style="white-space:pre"></span></script>

补充:

typeof操作符:对一个变量进行推断变量的类型,可能返回以下字符串:

"undefined" 如果这个值,未定义或者为初始化 

"boolean" 布尔值 

"string" 字符串 

"number" 数值 
"object" 对象 
"function" 函数 
用法:typeof 95;  或者  typeof(95); 会返回"number"示例代码:

<span style="white-space:pre"></span>var str = 'hello world';<span style="white-space:pre"></span>alert(typeof(str));<span style="white-space:pre"></span>//typeof 运算符的返回值有这么6种:"number," "string," "boolean," "object," "function," 和 "undefined." 



1 0