Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

类型的转换有哪些【热度: 631】 #540

Open
yanlele opened this issue Aug 31, 2023 · 1 comment
Open

类型的转换有哪些【热度: 631】 #540

yanlele opened this issue Aug 31, 2023 · 1 comment
Labels
JavaScript JavaScript 语法部分 滴滴 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Aug 31, 2023

关键词:js类型转换

可以将上述类型转换分为以下几类:

  1. 显式转换:显式转换是通过特定的函数或操作符来实现的,开发者明确地指定了类型转换的规则和目标类型。例如使用String()Number()Boolean()等函数进行类型转。

  2. 隐式转换:隐式转换是在特定的运算或操作中自动发生的,不需要开发者明确指定类型转换的规则和目标类型。例如在字符串拼接时,JavaScript会自动将其他类型转换为字符串类型;在使用比较操作符(如==><)进行比较时,JavaScript会自动进行类型转换以满足比较的要求。或者使用+-*/等操作符进行数值转换和计算。

  3. 强制转换:强制转换是指将一个类型强制转换为另一个类型,无论是显式转换还是隐式转换,都是通过强制转换来实现的。例如使用parseInt()parseFloat()等函数将字符串转换为数字类型;使用Boolean()函数将其他类型转换为布尔类型。

隐式转换在某些情况下可能会导致不可预测的结果,因此在开发中应尽量避免依赖隐式转换,而是通过显式转换来确保类型转换的准确性。


补充

在JavaScript中,有以下几种常见的类型转换方式:

  1. 转换为字符串:可以使用String()函数或toString()方法将其他类型的值转换为字符串类型。例如:

    var num = 42;
    var str = String(num); // 将数字转换为字符串
    var bool = true;
    var str2 = bool.toString(); // 将布尔值转换为字符串
  2. 转换为数字:可以使用Number()函数或使用parseInt()、parseFloat()等方法将其他类型的值转换为数字类型。例如:

    var str = "42";
    var num = Number(str); // 将字符串转换为数字
    var str2 = "3.14";
    var floatNum = parseFloat(str2); // 将字符串转换为浮点数
  3. 转换为布尔值:可以使用Boolean()函数将其他类型的值转换为布尔类型。例如:

    var num = 42;
    var bool = Boolean(num); // 将数字转换为布尔值
    var str = "hello";
    var bool2 = Boolean(str); // 将字符串转换为布尔值
  4. 隐式类型转换:JavaScript在某些情况下会自动进行类型转换,例如通过算术运算符、比较运算符等进行操作时,会根据需要隐式地将值转换为特定的类型。例如:

    var num1 = 42;
    var num2 = "3";
    var sum = num1 + Number(num2); // 隐式将字符串转换为数字并进行相加
@yanlele yanlele added JavaScript JavaScript 语法部分 滴滴 公司标签 labels Aug 31, 2023
@yanlele yanlele added this to the milestone Aug 31, 2023
@yanlele
Copy link
Member Author

yanlele commented Sep 29, 2023

参考文档: linwu-hi/code-interview#42

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript 语法部分 滴滴 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant