JavaScript int转string & string转int,测试代码如下:
<html>
<head>
<h1> JavaScript int2string/string2int test. </h1>
</head>
<body>
<script>
var id_str = "10";
var id_num = Math.floor( (Math.random()*10) ); //生成一个10以内的随机数、向下取整
// string2int
var a = parseInt(id_str);
var b = Number(id_str);
var c = eval(id_str);
// int2string
var d = id_num.toString();
var e = id_num + "";
console.log("id_str: " + id_str);
console.log("id_num: " + id_num);
console.log("------------");
console.log("string2int:")
console.log("result: " + a + ", type: " + typeof(a));
console.log("result: " + b + ", type: " + typeof(b));
console.log("result: " + c + ", type: " + typeof(c));
console.log("------------");
console.log("int2string:")
console.log("result: " + d + ", type: " + typeof(d));
console.log("result: " + e + ", type: " + typeof(e));
</script>
</body>
</html>
打印结果为:
id_str: 10
id_num: 2
------------
string2int:
result: 10, type: number
result: 10, type: number
result: 10, type: number
------------
int2string:
result: 2, type: string
result: 2, type: string