对存在JavaScript隐式类型转换的四种情况的总结

一般存在四种情况,JavaScript会对变量的数据类型进行转换。

目录


* if中的条件会被自动转为Boolean类型
	* 会被转为false的数据
	* 会被转为true的数据
* 参与+运算都会被隐式的转为字符串
	* 会被转为空字符串的数据
	* 会被转为字符串的数据
	* 会被转为数据类型标记的数据
* 参与*运算都会被隐式的转为数字
	* 会被转为0的数据
	* 会被转为1的数据
	* 会被转为NaN的数据
* == 运算符
	* 为true的时候
	* 为false的时候

if中的条件会被自动转为Boolean类型

会被转为false的数据


if(false) console.log(2333)
if('') console.log(2333)
if(null) console.log(2333)
if(undefined) console.log(2333)
if(NaN) console.log(2333)

会被转为true的数据


if(true) console.log(2333)  // 2333
if('test') console.log(2333)  // 2333
if([]) console.log(2333)  // 2333
if({}) console.log(2333)  // 2333

参与+运算都会被隐式的转为字符串

会被转为空字符串的数据


'str-' + ''  // str-
'str-' + []

会被转为字符串的数据


'str-' + '1'  // "str-1"
'str-' + 1  // "str-1"
'str-' + false  // "str-false"
'str-' + true  // "str-true"
'str-' + null  // "str-null"
'str-' + undefined  // "str-undefined"
'str-' + NaN  // "str-NaN"

会被转为数据类型标记的数据


'str-' + {}  // "str-[object Object]"
'str-' + {a:1}  // "str-[object Object]"

参与*运算都会被隐式的转为数字

会被转为0的数据


2 * ''  // 0
2 * []  // 0
2 * false  // 0

会被转为1的数据


2 * '1'  // 2
2 * [1]  // 2
2 * true  // 2

会被转为NaN的数据


2 * {}  // NaN
2 * {a:1}  // NaN

== 运算符

为true的时候


0 == false  // true
0 == ''  // true
0 == '0'  // true
0 == []  // true
0 == [0]  // true

1 == true  // true
1 == '1'  // true
1 == [1]  // true

[1] == true  // true
[] == false  // true

为false的时候


0 == {}  // false
0 == null  // false
0 == undefined  // false
0 == NaN  // false

1 == {}  // false
1 == null  // false
1 == undefined  // false
1 == NaN  // false

[] == []  // false
[1] == [1]  // false
[1] == {}  // false
[1] == {a:1}  // false
[1] == false  // false
[1] == null  // false
[1] == undefined  // false
[1] == NaN  // false

{} == {}  // false
{a:1} == {a:1}  // false

注:空数组[],在+运算符下是转为空字符串'',在*运算符下是转为数字0。但在if语句中,则转为true。

欢迎关注前端进阶指南微信公众号:

前端进阶指南

另外我也创了一个对应的QQ群:660112451,欢迎一起交流。

原文地址:https://www.cnblogs.com/bergwhite/p/7454789.html