Concatenation

type coercion

Automatic Type Conversion(自动类型转换)是 JavaScript 中的一个特性,它允许 JavaScript 在表达式中自动将值从一种数据类型转换为另一种类型。这通常发生在操作符需要两种不同数据类型的值时,JavaScript 会自动进行类型转换,以便操作可以顺利进行。

例如,当你尝试将字符串与数字相加时,JavaScript 会将数字转换为字符串并进行拼接。这个过程是自动进行的,而不需要显式地进行转换。

示例:

let number = 5;
let text = "The number is ";

let result = text + number;  // 这里数字 5 会被自动转换为字符串
console.log(result); // 输出: "The number is 5"

在上面的例子中,JavaScript 自动将数字 5 转换成了字符串 "5",然后与字符串 "The number is " 拼接。

常见的自动类型转换情况:

  1. 字符串和数字相加时,数字被转换为字符串:

    console.log("5" + 1);  // 输出 "51"(数字 1 被转换为字符串 "1")
    console.log(1 + "5");  // 输出 "15"
    
    
  2. 使用算术运算符时,字符串可以被转换为数字:

    console.log("5" - 1);  // 输出 4(字符串 "5" 被转换为数字 5)
    console.log("5" * 2);  // 输出 10(字符串 "5" 被转换为数字 5)
    
    
  3. 布尔值转换:

    console.log("5" + true);  // 输出 "5true"(true 被转换为字符串 "true")
    console.log("5" - true);  // 输出 4(true 被转换为数字 1)
    
    
  4. undefined 和 null 的转换:

    console.log("5" + undefined); // 输出 "5undefined"
    console.log("5" + null); // 输出 "5null"
    console.log(5 - null); // 输出 5 (null 转换为 0)
    console.log(5 - undefined); // 输出 NaN (undefined 转换为 NaN)
    
    

类型转换规则:

strings also follow the order of operations

截屏2024-12-11 16.42.01.png