JavaScript字符串和数字转换

JavaScript字符串和数字转换,第1张

JavaScript字符串和数字转换

您想熟悉

parseInt()
toString()

在您的工具箱中有用的是查看变量以找出它是什么类型的

typeof

<script type="text/javascript">        function printWithType(val) {        document.write('<pre>');        document.write(val);        document.write(' ');        document.writeln(typeof val);        document.write('</pre>');    }    var a = "1", b = "2", c = "3", result;    // Step (1) Concatenate "1", "2", "3" into "123"    // - concatenation operator is just "+", as long    //   as all the items are strings, this works    result = a + b + c;    printWithType(result); //123 string    // - If they were not strings you could do    result = a.toString() + b.toString() + c.toString();    printWithType(result); // 123 string    // Step (2) Convert "123" into 123    result = parseInt(result,10);    printWithType(result); // 123 number    // Step (3) Add 123 + 100 = 223    result = result + 100;    printWithType(result); // 223 number    // Step (4) Convert 223 into "223"    result = result.toString(); //    printWithType(result); // 223 string    // If you concatenate a number with a     // blank string, you get a string        result = result + "";    printWithType(result); //223 string</script>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5148737.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存