原文地址:https://dev.to/bhagatparwinder/javascript-type-conversion-14eg
转为 Boolean
JavaScript 中 Boolean 值有两个:true
和 false
。但是,JavaScript 还会把特定的值视为 truthy
和 falsy
。除了 0
、undefined
、""
、false
和 NaN
其它值都为 truthy
。
我们可以使用取反操作符 !
在 true 和 false 之间来回切换。这种转换也把数据类型转为了 boolean
。
const a = null;
const b = undefined;
const c = "";
const d = 0;
console.log(typeof a); // object
console.log(typeof b); // undefined
console.log(typeof c); // string
console.log(typeof d); // number
const w = !a;
const x = !b;
const y = !c;
const z = !d;
console.log(typeof w); // boolean
console.log(typeof x); // boolean
console.log(typeof y); // boolean
console.log(typeof z); // boolean
不仅把类型转为了 boolean ,还改变了变量的值。如果你需要转换 boolean 类型同时保持对应的 truthy
或 falsy
使用 !!
。
const a = null;
const b = undefined;
const c = "";
const d = 0;
console.log(typeof a); // object
console.log(typeof b); // undefined
console.log(typeof c); // string
console.log(typeof d); // number
const w = !!a;
const x = !!b;
const y = !!c;
const z = !!d;
console.log(typeof w); // boolean
console.log(typeof x); // boolean
console.log(typeof y); // boolean
console.log(typeof z); // boolean
// Let's check if they are all false though and haven't switched to true!
console.log(w); // false
console.log(x); // false
console.log(y); // false
console.log(z); // false
转为 String
使用 toString()
方法。
const num = 7;
console.log(typeof num); // number
const numString = num.toString();
console.log(typeof numString); // string
或使用便捷方式在后面添加 ""
。
const num = 7;
console.log(typeof num); // number
const numString = num + "";
console.log(typeof numString); // string
转为 Number
parseInt()
解析一个字符串为整数,你传递给它的字符串作为第一个参数,第二个参数作为基数。它指定使用哪个进制类型:hexadecimal (16), octal (8), or decimal (10)。
console.log(parseInt("0xF", 16)); // 15
console.log(parseInt("321", 10)); // 321
或者使用便捷方法在字符串之前添加 +
!
console.log(+"0xF"); // 15
console.log(+"321"); // 321
有些情况下 +
可能被用于字符串链接。在那种情况下,使用按位运算操作符 ~
两次:
console.log(~~"0xF"); // 15
console.log(~~"321"); // 321