Skip to content

类型转换

提纲

转换类型说明场景
ToPrimitive对象转基本数据类型* 隐式转换,如:[1] + 1
ToNumber转数值
ToBoolean转布尔
ToString转字符串

ToPrimitive

  • 核心:偏好(preferredType)
  • 当偏好算法返回一个值也不是基本数据类型时,不会递归,而是报错
  • 默认的偏好是数值,可以被覆盖
    • Date与Symbol已将偏好设置为字符串
  • 场景:
    • 对象参与运算:1 + {}

ToNumber

  • 基本规则:
    • 无法对Symbol进行转换,将会报错
    • undefined 被转为 NaN ,而 null被转为0
    • true 被转为 1false 被转为 0
    • 字符串转数值,转失败为 NaN
    • 对象先调用 ToPrimitive ,再调用 ToNumber
  • 场景:
    • Number([])
    • 1 - '1'

ToBigInt

  • 基本规则:
    • undefinednullsymbol 转换bigint类型均会报错
    • 对象先调用 ToPrimitive ,再转换

ToString

  • 基本规则:
    • undefined -> 'undefined'
    • null -> 'null'
    • true -> 'true'
    • false -> 'false'
    • symbol类型,报错
    • number类型调用 toString 方法
    • bigint类型调用 toString 方法
    • 对象先调用 ToPrimitive ,再调用 ToString
  • 场景:
    • '1' + []
    • '1' + Symbol.iterator

汇总

booleannumberstring
undefinedfalseNaN'undefined'
nullfalse0'null'
truetrue1'true'
falsefalse0'false'
0false0'0'
-0false-0'0'
+0false0'0'
NaNfalseNaN'NaN'
InfinitytrueInfinity'Infinity'
-Infinitytrue-Infinity'-Infinity'
''false0''
'0'true0'0'
'1'true1'1'
'-1'true-1'-1'
'hello'trueNaN'hello'
Symbol()ErrorError'Symbol()'

题目

javascript
let o = {};
o[1] = 1;
o['1'] = 2;
console.log(o); // { 1: 2 }
console.log(true + 1); // 2
console.log(true + '1'); // 'true1'
console.log(1 + 2 + 3); // 6
console.log('1' + '2' + '3'); // '123'
console.log(1 + 2 + '3'); // '33'
console.log(1 + 2 + '3' + 4 + 5); // '3345'
console.log(1 + 'A'); // '1A'
console.log(1 - 'A'); // NaN
console.log(1 + { a: 1 }); // '1[object Object]'
console.log(1 + [1, 2, 3]); // '11,2,3'
let x = {}, y = { a: 1 }, z = { a: 2 }, j = [3], k = [4];
x[y] = 5;
x[z] = 6;
x[j] = 7;
x[k] = 8;
console.log(x[y]); // 6
console.log(x[j]); // 7
console.log(x); // { '[object Object]': 6, 3: 7, 4: 8  }
javascript
let str = '1'
str = +!str
console.log(str) // 0
javascript
const x = '2' + 3 - true + '1'
console.log(x) // '221'