4. JavaScript 中隐秘的数据类型转换(Data Type Conversion)

133 阅读5分钟

JavaScript 中隐秘的数据类型转换(Data Type Conversion)

关键词:动态类型语言、运行时、编译时、类型检查、静态类型语言、数据类型转换、显式转换、隐式转换、手动转换、自动转换、字符串转换、数字转换、布尔值转换、算术运算、比较运算、逻辑运算、字符串拼接、条件语句、表达式

Keywords: Dynamically typed languages, runtime, compile time, type checking, statically typed languages, data type conversion, explicit conversion, implicit conversion, manual conversion, automatic conversion, string conversion, number conversion, Boolean conversion, arithmetic operations, comparison operations, logical operations, string concatenation, conditional statements, expressions

1 知识储备-JavaScript 是一门动态类型语言

JavaScript 是一门 动态类型语言。所谓 动态类型,是指 变量的类型运行时 确定,并且 在程序 执行过程中 改变,而 不需要 在定义时 指定具体类型

JavaScript is a dynamically typed language. The so-called dynamic type means that the type of a variable is determined at runtime and changes during program execution without specifying the specific type when defining it.

换句话说,JavaScript 的 变量类型根据赋值 动态决定 的,而不是一开始就固定的。

In other words, the variable type of JavaScript is determined dynamically based on the assignment, rather than being fixed from the beginning.

因为 类型是动态确定 的,JavaScript 并不会在 编译阶段 进行 类型检查,而是在代码 实际执行时 检查类型。

Because types are determined dynamically, JavaScript does not perform type checking at the compile time, but rather when the code is autually executed.

这让开发过程更加灵活,但 错误 也往往 出现在运行时,而不是在 编译时 就被发现。

This makes the development process more flexible, but errors tend to appear at runtime rather than being discovered at compile time.

let value = 42;         // `value` 是一个 number
console.log(typeof value); // 输出 "number"

value = "Hello";       // 重新赋值为字符串
console.log(typeof value); // 输出 "string"

value = true;          // 再次赋值为布尔值
console.log(typeof value); // 输出 "boolean"

而在 静态类型语言(如 JavaC++)中,变量的类型在编译时就确定了,且不能随意更改。

In statically typed languages (such as Java and C++), the type of a variable is determined at compile time and cannot be changed at will.

int number = 42;
number = "Hello"; // 编译错误,类型不匹配

动态类型语言的优缺点

Advantages and disadvantages of dynamically typed languages.

优点缺点
变量类型可根据需求随时更改,赋值 更灵活类型检查在运行时进行,数据的错误操作也会在运行时抛出,增加了调试难度
不需要提前声明类型,代码更简洁,更易于快速开发和迭代变量类型随时变化,导致 代码可读性下降
允许不同类型的数据在同一变量中交替使用,适合处理动态内容场景运行时需要不断判断变量类型,导致 性能下降

Advantages:

  • The variable type can be changed at any time according to the needs, and the assignment is more flexible
  • No need to declare types in advance, the code is more concise and easier to develop and iterate quickly
  • Allows different types of data to be used interchangeably in the same variable, whicih is suitable for handling dynamic content scenarios

Disadvantages:

  • Type checking is performed at runtime, and incorrect data operations will also be thrown at runtime, increasing the difficulty of debugging
  • Variable types change at any time, resulting in decreased code readability
  • The variable type needs to be constantly determined during runtime, resulting in performance degradation

2 JavaScript 的数据类型转换(Data Type Conversion)

JavaScript 具有 动态类型特性,允许 自动手动 在不同类型之间 进行 转换

JavaScript has a dynamic typing feature that allows automatic or manual conversion between different types.

2.1 数据类型转换的分类(Classification Of Data Type Conversion)

  • 显式 类型转换

    • 使用 内置函数 String()Number()Boolean() 进行 手动转换
  • 隐式 类型转换

    • 运算比较条件判断 等场景中 自动进行转换
  • Explicit Type Conversion

    • Manual conversion using the built-in functions String()Number()Boolean()
  • Implicit Type Conversion

    • Automatic conversion in scenarios such as calculate, comparison, conditional judgment, etc

2.2 显式类型转换(手动转换)

JavaScript 内置类型转换函数

2.3 隐式类型转换(自动转换)

隐式类型转换 通常 发生在: 算术运算比较运算(==逻辑运算 中。

Implicit type conversions typically occur in: arithmetic operations, comparison operations (==), and logical operations.

和显式类型转换一样,主要还是分为 字符串转换数字转换布尔值转换,只不过 隐式类型的转换过程是 隐藏的、自动发生的。

Like expilict type conversion, it is mainly divided into string conversion, number conversion and boolean conversion, but the impilict type conversion process is hidden and occurs automatically.

字符串转换(String Conversion)

字符串拼接操作(String Concatenation Operation)

let result = "The number is " + 5;
console.log(result); // 输出 "The number is 5"

规则:当 + 运算符 在任意一边是字符串时,JavaScript 会将另一边的数据类型 转换为 字符串,然后再执行 字符串拼接。

Rule: When the + operator has a string on either side, JavaScript converts th data of the other side to a string and then performs string concarenation.

具体规则参照:2.2 显式类型转换的转换函数 表格。

数字转换(Number Conversion)
console.log("5" - 2); // 输出 3
console.log("10" * "2"); // 输出 20
console.log(true + 1); // 输出 2
console.log(false - 1); // 输出 -1

规则:字符串 通过 算术运算符(除了 + 之外的 -*/)转换为 数字。

Rule: String are converted to numbers using arithmetic operators (-, *, / except +).

具体规则参照:2.2 显式类型转换的转换函数 表格。

布尔值转换(Boolean Conversion)

根据上述 2,2 表格,有 7 种 假值 情况,注意 有些情况可先通过 字符串转换 或 数字转换,再进行 布尔值转换。

There are 7 false values. Note that some cases can be converted to string or a number first, and then converted to a Boolean value.

条件语句中。JavaScript 会隐式地将 表达式 转换为 布尔值

In a conditional statement, JavaScript implicitly converts the expression to a boolean value.

具体规则参照:2.2 显式类型转换的转换函数 表格。

3 隐式类型转换带来的问题(Problems With Implicit Type Conversion)

console.log(1 + "1");  // "11",数字 1 转为字符串后拼接
console.log("5" - 1);  // 4,字符串 "5" 转为数字后相减
console.log(true + true); // 2,true 转为 1,1 + 1 = 2
console.log([] == false); // true,空数组转换为 ""

隐式类型转换地结果可能有些困惑,所以在写代码的时候 要注意到 隐式类型转换 的问题。