显示类型转换

🌈 Number() 把值转为数字

var a = '123';
console.log(typeof(Number(a)) + '-' + Number(a)); // number-123

a = '3.14';
console.log(typeof(Number(a)) + '-' + Number(a)); // number-3.14
a = 'true';
console.log(typeof(Number(a)) + '-' + Number(a)); // number-NaN
// hint: 非数

a = 'a';
console.log(typeof(Number(a)) + '-' + Number(a)); // number-NaN
// hint: 非数

a = '1a';
console.log(typeof(Number(a)) + '-' + Number(a)); // number-NaN
// hint: 非数
Number("0"); // 0
Number(""); // 0
Number("   "); // 0
Number(null); // 0
Number(false); // 0
Number([]); // 0
Number("\\n"); // 0
Number("\\t"); // 0

Number(true); // 1
Number('true'); // NaN

Number(undefined); // NaN
Number({}); // NaN
Number("x"); // NaN

🌈 parseInt 把值转为一个整数

var a = '123';
console.log(typeof(parseInt(a)) + '-' + parseInt(a)); // number-123

a = true;
console.log(typeof(parseInt(a)) + '-' + parseInt(a)); // number-NaN
// hint: 只管把数字转为整型,非数都是 NaN

a = null;
console.log(typeof(parseInt(a)) + '-' + parseInt(a)); // number-NaN
// hint: 同上

a = undefined;
console.log(typeof(parseInt(a)) + '-' + parseInt(a)); // number-NaN

a = NaN;
console.log(typeof(parseInt(a)) + '-' + parseInt(a)); // number-NaN

a = '3.14'
console.log(typeof(parseInt(a)) + '-' + parseInt(a)); // number-3
// hint: 直接把小数点扔掉

a = 'abc123';
console.log(typeof(parseInt(a)) + '-' + parseInt(a)); // number-NaN
// hint: 非数

a = '123abc';
console.log(typeof(parseInt(a)) + '-' + parseInt(a)); // number-123
// hint: 如果数字和字符串混合,字符串在前,转为非数;数字在前,转到下一个不是数字为止的数字

a = '123.22abc';
console.log(typeof(parseInt(a)) + '-' + parseInt(a)); // number-123

a = '23.927'
// parseInt(a) → 23
var a = '10';
console.log(parseInt(a, 16)); // 16
// hint: 第二个参数是基底,把xx进制的a转为10进制 xx范围 2~36
// 也就是按照数 16 次进 1 的说法,算成十进制的数 10 就应该是 16
// 也就是16进制的16才等于10进制的10

var a = 'b';
console.log(parseInt(a, 16));
// hint: 0123456789abcdef
// 第 0 位:b * 16 ^ 0 = 11 * 1 = 11
parseInt('123', 5); // 把 '123' 看做5进制的数,返回十进制的数38
// => 1 * 5 ^ 2 + 2 * 5 ^ 1 + 3 * 5 ^ 0 = 25+10+3 = 38