栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

Javascript基础教程之数据类型转换

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Javascript基础教程之数据类型转换

所有语言都有类型转化的能力,javascript也不例外,它也为开发者提供了大量的类型转化访法,通过全局函数,可以实现更为复杂的数据类型。

复制代码 代码如下:
var a = 3;
var b = a + 3;
var c = "student" + a;
var d = a.toString();
var e = a + "";
document.write(typeof(a) + " " + typeof (b) + " " +typeof (c) + " " + typeof (d) + " " + typeof (e));
//输出 number number string string string

 最简单的类型转化的例子

复制代码 代码如下:
var a=b=c=d=e=4;
var f = a+b+c+d+ c.toString();
document.write(f);
// 输出  结果 164

对于数据类型转为字符串,使用toString() Javascript转化为字符串同时实现机制转化。

复制代码 代码如下:
var a =111;
document.writeln(a.toString(2)+"
");
document.writeln(a.toString(3)+"
");
document.writeln(a.toString(8)+"
");
document.writeln(a.toString(10)+"
");
document.writeln(a.toString(16)+"
");
//执行结果
//
1101111
11010
157
111
6f

字符串转数值型,Javascript 使用parseInt()和parseFloat()可进行转化,正如方法的名称一样,前者将字符转化为整数,后者将字符转化为浮点数型。只有字符才能调运这两种方法,否则转化为NaN。不再进行任何操作。

parseInt()的先检查下标0处的字符,如果这个字符是有效字符,则检查1处的字符,如果不是有效字符,则终止转化。下面的例子是parseInt()的举例

复制代码 代码如下:
document.writeln(parseInt("4555.5544")+"
");
document.writeln(parseInt("0.5544")+"
");
document.writeln(parseInt("1221abes5544")+"
");
document.writeln(parseInt("0xc")+"
");//直接进行进制转化
document.writeln(parseInt("ahthw@hotmail.com")+"
");
//执行结果
4555
0
1221
12
NaN

利用parseInt,同样也可以轻松的实现进制转化。(parseFloat()和parseFlaot类似,这里不再举例。)

复制代码 代码如下:
document.writeln(parseInt("0421",8)+"
");
document.writeln(parseInt("0421")+"
");
document.writeln(parseInt("0421",16)+"
");
document.writeln(parseInt("AF",16)+"
");
document.writeln(parseInt("011",10)+"
");
//输出结果
273
421
1057
175
11

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/104474.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号