类型转化

2018-06-17  本文已影响0人  是小张啊啊

数值/字符串/function/undefined/对象(null/数组)

var a = "123";
var b = Number(a);
console.log(NaN === NaN);//返回的是fasle

var a = NaN;
console.log(a === a);//返回的还是fasle
var a = true;
var b = Number(a);//返回1
var a = undefined;
var b = Number(a);//返回NaN
var a = [];
var b = Number(a);//空数组,被解释为0

var a = ["1,2,3"];
var b = Number(a);//返回为123

var a = ["1,2,3","456"];
var b = Number(a);//数组中有多个值,返回为NaN
var a = null;
var b = Number(a);//返回0
NaN

判断一个值是否为NaN
isNaN();返回的是一个布尔值,内部其实是调用了Number()

var a = 122;
console.log(isNaN(a));//返回的是true

在运算中的类型转换

其他类型转字符串 + " "

var a = null;
a = a + " ";
console.log(typeof a);

其他类型转数值 用*1 或者/1

var a = "123";
a = a/1;
console.log(typeof a);

其他类型转布尔值 用双!!

var a = null;
a = !! a;
console.log(typeof a);
var a = null;
a ++;
console.log(typeof a);//返回1

var a = undefined;
a ++;
console.log(typeof a);//返回NaN

var a = "123";
a ++;//会有类型转换
console.log(a);//返回1234
a = a+1;
console.log(a);//返回1231
var a = "100px";
console.log(Number(a));//返回NaN
console.log(parseInt(a));//返回100

//不要用小数做判断
//小数被转化成二进制之后,可能无限循环,导致精度损失

var a = [];
console.log(parseInt(a));//返回NaN

var a = ["123"];
console.log(parseInt(a));//返回123

var a = ["123","456"];
console.log(parseInt(a));//只返回第一个值
toFixed();保留几位小数,将数值类型转化为字符串,将目标位的后一位进行四舍五入
var a =2.25344461949139149849011896;
console.log(a.toFixed(2));//返回2.25
console.log(a.toFixed(1));//返回2.3
上一篇下一篇

猜你喜欢

热点阅读