面试题答案
一键面试- 比较
'1'
和true
:- 结果:
'1' > true
为true
。 - 原因:在JavaScript中,关系操作符
>
和<
比较不同类型的值时,会先进行类型转换。true
会被转换为数字1
,'1'
会被转换为数字1
。但在比较'1' > true
时,由于true
先被转换为数字1
,而字符串和数字比较时,字符串会被转换为数字,所以'1'
转换为数字1
,此时比较1 > 1
为false
,但由于比较规则,先比较字符串和布尔值,字符串'1'
在这种比较规则下被认为大于true
转换后的1
,所以'1' > true
为true
。而'1' < true
为false
。
- 结果:
- 比较
null
和undefined
:- 使用
>
:- 结果:
null > undefined
为false
。 - 原因:
null
和undefined
在进行大于比较时,null
会被转换为0
,undefined
会被转换为NaN
,而NaN
与任何值比较(包括它自身)结果都为false
,所以null > undefined
为false
。
- 结果:
- 使用
<
:- 结果:
null < undefined
为false
。 - 原因:同理,
null
转换为0
,undefined
转换为NaN
,NaN
参与比较结果都为false
,所以null < undefined
为false
。
- 结果:
- 使用
==
:- 结果:
null == undefined
为true
。 - 原因:在JavaScript中,
null
和undefined
有特殊的相等比较规则,它们彼此相等,这是语言设计的特性。而null === undefined
为false
,因为严格相等(===
)要求类型和值都相同,null
类型是null
,undefined
类型是undefined
,类型不同。
- 结果:
- 使用