var str = "Hello, world";//字符串
var i = 10;//整型数
var f = 2.3;//浮点数
var b = true;//布尔值
var func = function(){ //function
alert("I am a function here");
};
var obj = new Object(); //Object
obj.name = "gerry";
obj.age = 23;
var arr = new Array("foo", "bar", "zoo"); //数组
var str2 = new String("JavaScript Kernal");//字符串对象
//测试
//typeof 返回的是字符串,有六种可能:"number"、"string"、"boolean"、"object"、"function"、"undefined"
alert("typeof str=="+typeof str);//输出string
alert("typeof i=="+typeof i);//输出number
alert("typeof f=="+typeof f);//输出number
alert("typeof b=="+typeof b);//输出boolean
alert("typeof func=="+typeof func);//输出function
alert("typeof obj=="+typeof obj);//输出object
alert("typeof arr=="+typeof arr); //输出object
alert("typeof str2=="+typeof str2);//输出object
//可以将typeof操作符和instanceof操作符结合起来进行判断
alert(obj instanceof Array);//false
alert(arr instanceof Array);//true
//对象的constructor属性:每个javascript对象都有一个constructor属性.这个属性对应了对象初始化时的构造函数(函数也是对象)
//constructor说明:表示创建对象的函数。始终指向创建当前对象的构造函数
//typeof可以检查到变量是否有定义,而construct只能检查已定义变量的类型。
alert("str.constructor=="+str.constructor);//输出function String(){[native code]}
alert("i.constructor=="+i.constructor);//输出function Number(){[native code]}
alert("f.constructo=="+f.constructor);//输出function Number(){[native code]}
alert("b.constructor=="+b.constructor);//输出function Boolean(){[native code]}
alert("func.constructor=="+func.constructor);//输出function Function(){[native code]}
alert("obj.constructor=="+obj.constructor);//输出function Object(){[native code]}
alert("arr.constructor=="+arr.constructor);//输出function Array(){[native code]}
alert("str2.constructor=="+str2.constructor);//输出function String(){[native code]}
alert("typeof(str.constructor)=="+typeof(str.constructor));//输出function
alert("typeof(i.constructor)=="+typeof(i.constructor));//输出function
alert("typeof(f.constructor)=="+typeof(f.constructor));//输出function
alert("typeof(b.constructor)=="+typeof(b.constructor));//输出function
alert("typeof(func.constructor)=="+typeof(func.constructor));//输出function
alert("typeof(obj.constructor)=="+typeof(obj.constructor));//输出function
alert("typeof(arr.constructor)=="+typeof(arr.constructor));//输出function
[b]变量转换[/b]
使用原始数据类型(有时也称为字面量)来转换变量,这种没有任何额外的影响的做法反而效率更高。
var myVar = "3.14159",
str = ""+ myVar,// to string
int = ~~myVar, // to integer
float = 1*myVar, // to float
bool = !!myVar, /* to boolean - any string with length
and any number except 0 are true */
array = [myVar]; // to array