JavaScript中的基本类型转换

概念

   在JS语言中,一个基本类型的数据可以隐式地转化为其他的基本类型的数据。什么意思呢?在JS中,主要分为两种数据类型,保存在栈中的数据,被称为原始数据类型或基本类型。保存在堆里的数据,被称为引用数据类型,因为访问这种类型的方式是通过引用进行访问的。而基本类型的值之间可以不同过明显的方式进行转化,显式地转化方式举个例子。

1
2
3
var str = '3';
var num = Number(str); //3
console.log(typeof num); // 'number';

   而隐式转换则为未通过这种明显的方式进行数据类型的转化。

常见场景

  1. 在if语句的判断条件中,string类型的值,空字符串’’会转化为布尔值false,非空字符串则会转化为布尔值true。number基本类型的值,数字0会转化为false, 其他数字会转化为true。undefined和null值都会转化为false。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var emptyStr = '',
someStr = 'hello';
if(emptyStr) {
console.log('Hello world!');
} else if(someStr) {
console.log('Bye world!');
} else {
console.log('Fuck world');
}
// 'Bye world'

var numberZero = 0,
someNum = 4396;
if(numberZero) {
console.log('Zero will not transform to fasle.')
} else if(someNum) {
console.log('Zero will transform to false, and someNum will transform to true');
} else{
console.log('Haha, number can\'t tranform to Boolean');
}
// 'Zero will transform to false, and someNum will transform to true'

var undefinedValue,
nullValue = null;
if(!undefinedValue && !nullValue) {
console.log('undefined and null will transform to fasle');
} else {
console.log('They won\'t');
}
\\ 'undefined and null will transform to fasle'
  1. 在==判断中,能够转化为相同的布尔值则会返回true