# 隐式转换

toString 和 valueOf

toString:toString()函数的作用是返回object的字符串表示

Array 返回数组元素的字符串,默认以逗号链接。 Boolean 布尔值的字符串值 Date 日期UTC标准格式 Function 函数的字符串值 Number 数字值的字符串值 Object [Object Object] String 字符串值 Reg 正则的字符串值

valueOf:valueOf()函数将对象转换为原始值

Array 返回数组对象本身 Boolean 布尔值 Date 返回时间是从 1970 年 1 月 1 日午夜开始计的毫秒数 UTC Function 函数本身 Number 数字值 Object 对象本身,这是默认情况。 String 字符串值 Reg 正则本身

隐式转换介绍

  • 在js中,当运算符在运算时,如果两边数据不统一,CPU就无法计算,这时我们编译器会自动将运算符两边的数据做一个数据类型转换,转成一样的数据类型再计算

  • 这种无需程序员手动转换,而由编译器自动转换的方式就称为隐式转换

  • 例如1 > "0"这行代码在js中并不会报错,编译器在运算符时会先把右边的"0"转成数字0`然后在比较大小

转换为字符串 转换为数字 转换为布尔值 转换为对象
undefined 'undefined'
NaN
false throws TypeError
null 'null' 0 false throws TypeError
true 'true' 1 new blean(true)
fasle 'flase' 0 new blean(false)
''(空字符串) 0 false new String('')
'1.2'(非空,数字) 1.2 true new String('1.2')
'one'(非空,非数字) NaN true new String('one')
0 '0' false new Number(0)
-0
'0'
false new Number(-0)
NaN 'NaN false new Number(NaN)
Infinty 'Infinty' true new Number(Infinty)
-Infinty '-Infinty' true new Number(-Infinty)
1(无穷大,非零) '1' true new Number(1)
{} [Onject object] true
[] '' 0 true
[9](一个数字元素数组) '9' 9 true
['a'](其他数组) 使用join方法 NaN true
function(){}(任意函数) 函数的字符串值 NaN true

toString()函数的作用是返回object的字符串表示

Array 返回数组元素的字符串,默认以逗号链接。 Boolean 布尔值的字符串值 Date 日期UTC标准格式 Function 函数的字符串值 Number 数字值的字符串值 Object [Object Object] String 字符串值 Reg 正则的字符串值

隐式转换规则

  • 1.转成string类型: +(字符串连接符)

  • 2..转成number类型:++/--(自增自减运算符) + - * / %(算术运算符) > < >= <= == != === !=== (关系运算符)

  • 3.转成boolean类型:!(逻辑非运算符)

6种假值 :null、undefined、‘’、0、NaN 、false

字符串连接符与算术运算符隐式转换规则混淆

· 常见面试题如下

· 原理分析

关系运算符:会把其他数据类型转换成number之后再比较关系

常见面试题如下

· 原理分析

复杂数据类型在隐式转换时会先转成String,然后再转成Number运算

· 原理分析

逻辑非隐式转换与关系运算符隐式转换搞混淆

  • 对象转换为字符串和对象到数字的转换是调用带转换对象的一个方法来完成的。 toString与valueOf toString返回一个反应这个对象的字符串 ->:[object object] 特殊场合:[1,2,3].toString()-> 1,2,3 (function a(){ f(x); }).toString()->function(x){\n f(x); \n} /\d/g.toString() -> /\d/g new Date(2010,0,1).toString() -> 国际化时间 valueOf()他默认将对象转换为表示它的原始值,因为对象是复合值,所以简单返回对象本身,,日期对象会返回 太平洋时间。

  • 对象转数字首先找valueOf 如果没有->toString 没有->抛出异常 对象转字符串 toString->valueOf->抛出异常

· 前方高能,请注意~

空数组的toString()方法会得到空字符串,而空对象的toString()方法会得到字符串[object Object] (注意第一个小写o,第二个大写O哟)

· 常见面试题

· 原理分析

见过的一些面试题

console.log(1+ "true")
console.log(1+ true)
console.log(1+ undefined)
console.log(1 + null)
console.log(1+ [])
console.log(1+ {})
console.log(1+ new Date())
console.log(1+ new ArrayBuffer())
console.log(1+NaN)
console.log(1+ false)
console.log(1+function(){})
console.log(1+/w/g)

var a = {},b={},c=[],d=[]
console.log(a==b)
console.log(c==d)
console.log("2">3)
console.log("2">"3")
console.log(NaN == NaN)
console.log(null == null)
console.log(undefined ==undefined)
console.log(NaN == null)
console.log(null ==undefined)
console.log([] == 0)
console.log([] == ![])
console.log({} == !{})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Last Updated: 4/15/2020, 5:02:25 PM