本文详解JavaScript中数值与字符串在不同进制间的转换方法。通过示例演示如何利用toString()指定基数将数字转为二进制等字符串,以及使用parseInt()解析带进制的字符串为数值,涵盖数组处理与基础类型转换的实际应用。
JavaScript进制转换概述
在JavaScript中,进行数值与字符串的相互转换时,支持指定不同的进制基数进行操作。
具体的转换示例如下所示。
数值与字符串互转代码示例
相关代码实现如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>带进制的数值和字符串间进行转换</title>
</head>
<body>
<script language="javascript">
//数字到串的转换:toString(),可转化为不同进制
function test1(){
var f = [1,2,3,4,5,6,7,8];
alert(f.reverse().join("")); //数组的反向功能,连接功能测试
var b = parseInt(f.reverse().join("")).toString(2);
alert(b);
}
//字符到数值的转换:parseInt(),可转换不同进制的数据
function test2(){
var s = '10101010';
var b = parseInt(s,2);
alert(b);
}
test2();
</script>
</body>
</html>