Javascript类型转换

1. 原始转换数字

Number(true) // 1
Number(false) // 0
Number(null) // 0
Number(undefined) // NaN 
console.log(Number("")); // 0
console.log(Number("1")); // 1
console.log(Number("abc")); // NaN

parseInt函数数组转换规则

parseInt函数接收两个参数

  1. string

string参数必须是字符串。如果不是,通过tostring转换为String类型值.string参数字符串从左侧第一个字符开始查找,查找出符合radix进制的值,如果遇到不符合的直接结束查找,不管后面是否有符合的字符。找到的内容按照radix的进制转换为10进制。

  1. radix

radix参数为进制基数。如果不写/为零,radix则默认为10(特殊情况下 如果字符串是以0x开头的话,默认值为16)有效范围2~36 如果不在此范围,函数直接返回NaN。

parseInt("10102px13", 2) // 10
/*
1. "10102px13"在二进制中只有0/1 所以符合字符串为'1010'
2. 将上述字符串 按权展开求和
1*2^3+0*2^2+1*2^1+0*2^0 = 8+0+2+0 => 10
因此输出10
*/
parseInt(null) // NaN
/*
1. null => 'null'
2. 'null'中没有效果字符因此返回NaN
*/

再来看看一道面试题

let arr = [27.2, 0, '0013', '14px', 123]
arr = arr.map(parseInt)
console.log(arr) // [27, NaN, 1, 1, 27]
/*
arr.map(parseInt) 依次执行
parseInt(27.2, 0) => parseInt('27', 10) => 27
parseInt(0, 1) => 1不在2~36的返回因此输出NaN
parseInt('0013', 2) => parseInt('001', 2) => 0*2^2+0*2^1+1*2^0 => 0 + 0 + 1 => 1
parseInt('14px', 3) => parseInt('1', 3) => 1*3^0 => 1
parseInt(123, 4) => parseInt('123', 4) => 1*4^2+2*4^1+3*4^0 => 16 + 8 + 3 => 27
因此可见
arr = [27, NaN, 1, 1, 27]
*/

parseInt(‘0013’, 2)输出为 1;如果是’0013’改为0013数字结果则为3

具体步骤

parseInt(0013, 2) // 3
/*
1. 0013按照8转换为10进制
0*8^3+0*8^2+1*8^1+3*8^0 => 0 + 0 + 8 + 3 => 11
2. parseInt(11, 2)
1*2^1 + 1*2^0 => 2 + 1 => 3
因此输出3
*/

[!NOTE]

JS中遇到以0为开头的数字 会默认按照8 转为 10进制 然后再进行其他操作。

2. 所有类型转换布尔类型

console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(0)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean(1)); // true
console.log(Boolean("")); // false
console.log(Boolean("aa")); // true
console.log(Boolean({})); // true
console.log(Boolean([])); // true

除了null、undefined、0、NaN、空字符串转换为false,其余类型转换都为true

3. 原始类型转换字符串

console.log(null + ""); // 'null'
console.log(undefined + ""); // 'undefined'
console.log(123 + ""); // '123'
console.log(true + ""); // 'true'
console.log(false + ""); // 'false'

4. 对象转换为原始

对象转为原始时先判断是否有Symbol.toPrimitive属性,有则调用此属性方法,如果没有则调用对象的valueOf方法,判断是否是一个原始类型如果是,则返回原始值,如果不是继续调用toString方法

var obj = {}
// 1 obj[Symbol.toPrimitive] undefined
// 1. obj.valueOf() => {}
// 2. obj.toString() => '[object Object]'
console.log(+obj) // 因此 打印NaN 因为'[object Object]'不是一个数字
// 如果改写了valueOf方法
obj.valueOf = function () {
  return 1
}
console.log(+obj) // 1

5. 面试题

// 如何使下面代码打印true
console.log(a == 1 && a == 2 && a == 3);

思路:

  1. a如果要使其三个等号为都为真的话,原始类是一定不行的;只有对象。

  2. a是对象的话,首先会调用valueOf方法尝试转换为数字

  3. 看比较的顺序来看a是递增加1.

因此可以编写如下代码:

var a = {
  value: 0,
  valueOf() {
    return ++this.value
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值