编程语言
首页 > 编程语言> > Javascript中类型转换的情况以及结果

Javascript中类型转换的情况以及结果

作者:互联网

    * 会被转为false的数据
    * 会被转为true的数据
    * 会被转为空字符串的数据
    * 会被转为字符串的数据
    * 会被转为数据类型标记的数据
    * 会被转为0的数据
    * 会被转为1的数据
    * 会被转为NaN的数据
    * 为true的时候
    * 为false的时候
   
  1. if中的条件会被自动转为Boolean类型
if(false) console.log(2333)
if('') console.log(2333)
if(null) console.log(2333)
if(undefined) console.log(2333)
if(NaN) console.log(2333)
if('test') console.log(2333)  // 2333
if([]) console.log(2333)  // 2333
if({}) console.log(2333)  // 2333
  1. 参与+运算都会被隐式的转为字符串
    1. 转换为空字符串
'str-' + ''  // str-
'str-' + [] // str-
b. 转成字符串的数据
'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"
c.转成数据类型标记
'str-' + {}  // "str-[object Object]"
'str-' + {a:1}  // "str-[object Object]"
  1. 参与*运算都会被隐式的转为数字
    1. 会被转为0的数据
3 * ''  // 0
3 * []  // 0
3 * false  // 0
2 * '1'  // 2
2 * [1]  // 2
2 * true  // 2
2 * {}  // NaN
2 * {a:1}  // NaN
4. == 运算符 a.会被转为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
b.会被转为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
PS:空数组[],在+运算符下是转为空字符串'',在*运算符下是转为数字0。但在if语句中,则转为true

标签:类型转换,2333,false,结果,转为,Javascript,NaN,str,true
来源: https://www.cnblogs.com/wangxue13/p/13568208.html