JS-转换类型

2018-11-07  本文已影响0人  远方的路_

转换为字符串类型

// number类型
var num = 123;
var res = num.toString();
console.log(res); // 在谷歌浏览器中String类型输出之后是灰色的
console.log(typeof res); // string
console.log(num); // 在谷歌浏览器中Number类型输出之后是蓝色的
console.log(typeof num);
// Boolean布尔类型
var flag = true;
var res2 = flag.toString();
console.log(res2);
// null和 undefined
var n = null;
var res3 = n.toString(); // 会报错
var u = undefined;
var res4 = u.toString(); // 会报错
var num = 123;
var res1 = String(num);
console.log(res1);  // 123
console.log(typeof res1); // string

var flag = false;
var res2 = String(flag);
console.log(res2); // false

var n = null;
var res3 = String(n);
console.log(res3); // null

var u = undefined;
var res4 = String(u);
console.log(res4); // undefined
var num = 123;
var flag = true;
var n = null;
var u = undefined;

// 任何类型和字符串相加, 都会先转换为字符串之后再相加
var res1 = num + ""; // 123 + ""  --> "123" + "" --> "123"
console.log(res1); // 123
console.log(typeof res1); // string

var res2 = flag + "";
console.log(res2); // true

var res3 = n + "";
console.log(res3); // null

var res4 = u + "";
console.log(res4); // undefined

转换为Number类型

var str1 = "123";
var res1 = +str1;
console.log(res1); // 123
console.log(typeof res1); // number

var res2 = -str1;
console.log(res2); // -123
console.log(typeof res2); // number

var str2 = "3.14";
var res3 = +str2;
console.log(res3); // 3.14

var flag1 = true;
var res4 = +flag1;
console.log(res4); // 1

var flag2 = false;
var res5 = +flag2;
console.log(res5); // 0

var n = null;
var res6 = +n;
console.log(res6); // 0

var u = undefined;
var res7 = +u;
console.log(res7); // NaN
var str1 = "3.14px";
var res1 = parseInt(str1);
console.log(res1); // 3
console.log(typeof res1); // number

var res2 = parseFloat(str1);
console.log(res2); // 3.14
console.log(typeof res2); // number

var str = "12px666px";
var res1 = parseInt(str);
console.log(res1); // 12

var str = "3.14.15px";
var res1 = parseFloat(str);
console.log(res1); // 3.14

转换为Boolean类型

上一篇下一篇

猜你喜欢

热点阅读