JavaScript int转string & string转int

这段代码展示了如何在JavaScript中将字符串转换为整数(string2int)和将整数转换为字符串(int2string),使用了parseInt、Number和eval函数进行字符串转整数,以及toString和加空字符串方法进行整数转字符串。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunny05296

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值