JavaScript 字符串和数字转换

标签 javascript string numbers

如何在 JavaScript 中执行以下操作?

  1. 将“1”、“2”、“3”拼接成“123”

  2. 将“123”转换为123

  3. 123 + 100 = 223

  4. 将223转化为“223”

最佳答案

您想熟悉parseInt()toString() .

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

<script type="text/javascript">
    /**
     * print out the value and the type of the variable passed in
     */

    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>

关于JavaScript 字符串和数字转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/971039/

相关文章:

javascript - 使用 Angular 根据重复项的数量设置类?

javascript - crossfilter.js,如何处理日期维度上的人为重复项

javascript - 无法获取 HTML ANCHOR + 如何覆盖 anchor 的 .onclick

java - 在 Java 中将十进制数转换为十六进制字符串失败

c++ - string.compare 什么时候停止比较? (标准)

c# - 使用 Blum Blum Shub 算法的伪随机数生成器

javascript - "inner"要求的 Dojo 范围问题

c++ - std::erase 在循环中计算重复字符时崩溃?

objective-c - 在 Objective C 中为 iPhone SDK 生成随机数

ruby - 在 Ruby 中定义求和函数