JS中数据类型的转换

转换为数字类型 Number

字符串转数字类型

Number('1')===1;
parseInt('1',10)===1;
parseFloat('1.1')===1.1;
X -0
+ X

转换为字符串类型

String

String(1);//"1"
String(true);//"true"
String(null);//"null"
String(undefined);//"1"
String({});//"[object Object]"

toString

(1).toString();//"1"
true.toString();//"true"

null.toString();//报错
//Uncaught TypeError: Cannot read property 'toString' of null

undefined.toString();//报错
//Uncaught TypeError: Cannot read property 'toString' of undefined

{}.toString();//报错
//Uncaught SyntaxError: Unexpected token .

[{}].toString();//"[object Object]"

+ ''

1+'' //"1"
true+'' //"true"
null+""//"null"
undefined+'' //"undefined"
{}+'' //0

var e={};
e+'';//"[object Object]"

转布尔类型

Boolean(x)
Boolean('')//false
Boolean({})//true

!!x

五个falsy值:

0

NaN

null

undefined

在布尔上下文中认定可转为false的值

原文地址:https://www.cnblogs.com/BUBU-Sourire/p/11094503.html