javascript中数据类型

本文介绍了JavaScript中的基本数据类型,包括字符串、整型数、浮点数、布尔值等,并展示了如何使用typeof和instanceof操作符来判断变量类型。此外,还提供了变量转换的方法,例如字符串转换为数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值