JavaScript 什么是类型转换

JavaScript 什么是类型转换

类型转换 指的是自动或隐式将一个数据类型的值转换为另一个数据类型的过程。这包括在应用不同类型的操作符时,从Number转换为String,从String转换为Number,从Boolean转换为Number等等。

如果对隐式转换的行为不确定,可以使用数据类型的构造函数将任何值转换为该数据类型,例如 Number()String()Boolean() 构造函数。

1. Number转换为String: 当任何字符串或非字符串值添加到字符串时,它总是将非字符串值隐式转换为字符串。当字符串’Rahul’被添加到数字10时,JavaScript不会报错。它使用类型转换将数字10隐式转换为字符串’10’,然后连接两个字符串。下面是一些更多的示例。

示例:

// The Number 10 is converted to 
// string '10' and then '+' 
// concatenates both strings    
var x = 10 + '20'; 
var y = '20' + 10; 
  
// The Boolean value true is converted 
// to string 'true' and then '+' 
// concatenates both the strings 
var z = true + '10'; 
  
console.log(x); 
console.log(y); 
console.log(z);

输出:

1020
2010
true10

2. 将字符串转为数字: 当进行减法(-)、乘法(*)、除法(/)或取模(%)等操作时,所有不是数字的值都会被转换为数字数据类型,因为这些操作只能在数字之间进行。下面是一些示例。

示例:

// The string '5' is converted 
// to number 5 in all cases 
// implicitly 
var w = 10 - '5'; 
var x = 10 * '5'; 
var y = 10 / '5'; 
var z = 10 % '5'; 
  
console.log(w); 
console.log(x); 
console.log(y); 
console.log(z);

输出:

5
50
2
0

3. 布尔值转换成数字: 当一个布尔值与一个数字相加时,布尔值会被转换成数字,因为将布尔值转换成数字值更安全和更容易。一个布尔值可以用0表示“false”,用1表示“true”。以下是一些示例。

示例:

// The Boolean value true is 
// converted to number 1 and 
// then operation is performed 
var x = true + 2; 
  
// The Boolean value false is 
// converted to number 0 and 
// then operation is performed 
var y = false + 2; 
  
console.log(x); 
console.log(y);

输出:

3
2

4. 相等运算符: 相等运算符(==)可以用来比较值,不考虑它们的类型。这是通过将非数字数据类型强制转换为数字来实现的。以下是一些示例:

示例:

// Should output 'true' as string '10' 
// is coerced to number 10 
var x = (10 == '10'); 
  
// Should output 'true', as boolean true 
// is coerced to number 1 
var y = (true == 1); 
  
// Should output 'false' as string 'true' 
// is coerced to NaN which is not equal to 
// 1 of Boolean true 
var z = (true == 'true'); 
  
console.log(x); 
console.log(y); 
console.log(z);

输出:

true
true
false

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程