JavaScript 进阶营

JS数据类型转换

2018-12-06  本文已影响0人  哎呦_連啓

转布尔值

Boolean类型只有两个字面值:true和false。
在条件判断时会出现假的(false)情况为:“ ”,0,NaN,null,undefined,false,只有这几种情况转换为false;与之相反的,什么为真呢?其实除了假都是真,包括所有对象。

转字符串

var colors = ['red','blue','green'];
var num = 123;
var found = true;
console.log(colors.toString()); //"red,blue,green"
console.log(num.toString());    //"123"
console.log(found.toString());  //"true"
var colors = ['red','blue','green'];
var num = 123;
var found = true;
console.log(String(colors)); // "red,blue,green"
console.log(String(num));    // "123"
console.log(String(found));  // "true"
console.log(String(null));  // "null"
console.log(String(undefined));  // "undefined"

转number数据类型

其他类型转number类型主要有Number(),parseFloat(),parseInt()这三种强制类型转换

console.log(Number(123));   //123
console.log(Number('123')); //123
console.log(Number('123aa'));   //NaN
console.log(Number(''));   //0
console.log(Number([]));   //0
console.log(Number(null));   //0
console.log(Number(false));   //0
console.log(Number(true));   //1
console.log(Number(undefined));   //NaN
console.log(parseInt(123)); //123
console.log(parseInt(123.23)); //123
console.log(parseInt('123.23')); //123
console.log(parseInt('123aa')); //123
console.log(parseInt('.123aa')); //NaN
console.log(parseInt('abc')); //NaN
console.log(parseInt('abc123')); //NaN
console.log(parseFloat(123)); //123
console.log(parseFloat(123.23)); //123.23
console.log(parseFloat('123.23')); //123.23
console.log(parseFloat('123aa')); //123
console.log(parseFloat('.123aa')); //0.123
console.log(parseFloat('ab123.23aa')); //NaN
console.log(parseFloat('abc')); //NaN
上一篇下一篇

猜你喜欢

热点阅读