解释 Javascript 中的类型转换?
JavaScript 中的类型转换意味着将一种数据类型转换为另一种数据类型,即将字符串数据类型转换为布尔值或将整数数据类型转换为字符串数据类型。JavaScript 中的类型转换也称为类型转换或类型强制。
转换类型
JavaScript 中的类型转换有两种类型。它们是隐式类型转换和显式类型转换。
隐式类型转换
隐式类型转换是由于内部要求或编译器或解释器自动转换而进行的数据类型转换。
为了理解隐式转换,让我们考虑布尔值(原始值)的示例。
JavaScript 在条件表达式中需要一个布尔值。因此 JavaScript 会暂时将括号中的值转换为布尔值来评估 if 表达式 −
示例
val = 1; if (val) { console.log( 'yes, val exists' ); }
值 0、-0、''(空字符串)、NaN、undefined 和 null 的计算结果为 false,所有其他值(甚至是空数组和对象)的计算结果为 true。
使用 == 运算符进行隐式转换
使用等号 (==) 和不等号 (!=) 运算符比较值时也会执行类型转换。因此,当您使用等号 (==) 运算符将数字 125 与字符串 '125' 进行比较时,表达式的计算结果为 true −
console.log( 125 == '125' );
使用相同 (===) 和不相同 (!==) 运算符时不会执行类型转换。
显式类型转换
第二种类型转换(显式类型转换)是由开发人员为了写出好的代码而强制执行的。在 JavaScript 中,类型转换只能针对字符串、数字和布尔(对象)数据类型进行。
显式类型转换的示例包括方法 parseInt()、parseFloat() 和 toString()。
parseInt() 函数将其第一个参数转换为字符串,解析该字符串,然后返回整数或 NaN。
parseFloat() 函数解析参数(如果需要,先将其转换为字符串)并返回浮点数。
toString() 方法返回表示对象的字符串,即,它尝试将对象转换为字符串。
示例
以下示例演示了 JavaScript 中的显式类型转换。
let a = 1.015 console.log(a) console.log(typeof a) console.log(a.toString()) console.log(typeof a.toString())
字符串中的类型转换
在 JavaScript 中,字符串被视为对象。因此,在字符串类型转换中,任何给定的数字或字符都将转换为字符串。String() 用于将任何给定值转换为字符串。
语法
可以使用以下语法对字符串进行类型转换。
String(input)
String() 方法将接受一个参数,即要转换为字符串的输入。
示例
以下是此函数的一个示例 -
input = 25 console.log("The input value with its type is:",input,typeof(input)) console.log("Arithmetic operation before typecasting with its type is:", (10 + input), typeof((10 + input))) sInput = String(input) console.log("After the type casting is done the type is:",sInput,typeof(sInput)) console.log("Arithmetic operation after typecasting with its type is:", (10 + sInput), typeof(10 + sInput))
在上面的例子中,给定的输入是一个数字,它在类型转换完成之前会进行数字相加。但是当给定的输入通过 String() 方法转换为字符串时,它不是将输入与 10 相加,而是将其连接起来,因为其中一个操作数是字符串,而另一个是数字。这表明类型转换已完成。
布尔值中的类型转换
要将给定的输入转换为布尔值,可以使用 Boolean(),它将给定的值作为参数并将其转换为布尔形式。此方法相应地返回布尔值"true"或"false"。如果输入至少是一个字符、任何除零以外的数字或它是一个对象,则返回 true。当给定的输入为空字符串、零未定义或空值时,它返回 false。
示例
以下是 JavaScript 中使用 Boolean() 进行布尔类型转换的示例 −
console.log("The cases where the method will return true") console.log("The given input is rw",Boolean('rw')) console.log("The given input is -3.6",Boolean(-3.6)) console.log("The given input is new Date()",Boolean(new Date())) console.log("The cases where the method will return false") console.log("The given input is number 0",Boolean(0) ) console.log("The given input is null value",Boolean(null) ) console.log("The given input is undefined",Boolean(undefined)) console.log("The given input is empty string",Boolean('') )
数字类型转换
要将给定的输入转换为数字,请使用 Number() 方法。该方法需要一个参数,即要转换为数字的输入。转换可以转换为浮点类型或整数类型。
要将其转换为整数类型,请使用 parseInt() 方法。要将其转换为浮点类型,请使用 parseFloat()。
语法
Number(input) parseInt(input) parseFloat(input)
这三种方法将以给定的输入作为参数,并根据所使用的方法进行转换。
示例
此示例演示了 JavaScript 中的 Number() 类型转换 −
console.log("Input is 7.8.9 and after conversion",Number("7.8.9")) console.log("Input is 6.6.6 and after conversion to float is",parseInt("6.6.6")) console.log("Input is 6.6.6 and after conversion to float is",parseFloat("6.6.6"))