将 "switch" 结构重写为 "if" 结构
重要程度: 5
将下面 switch
结构的代码写成 if..else
结构:
switch
(
browser)
{
case
'Edge'
:
alert
(
"You've got the Edge!"
)
;
break
;
case
'Chrome'
:
case
'Firefox'
:
case
'Safari'
:
case
'Opera'
:
alert
(
'Okay we support these browsers too'
)
;
break
;
default
:
alert
(
'We hope that this page looks ok!'
)
;
}
为了精确实现 switch
的功能,if
必须使用严格相等 '==='
。
对于给定的字符串,一个简单的 '=='
也可以。
if
(
browser ==
'Edge'
)
{
alert
(
"You've got the Edge!"
)
;
}
else
if
(
browser ==
'Chrome'
||
browser ==
'Firefox'
||
browser ==
'Safari'
||
browser ==
'Opera'
)
{
alert
(
'Okay we support these browsers too'
)
;
}
else
{
alert
(
'We hope that this page looks ok!'
)
;
}
请注意:将 browser == 'Chrome' || browser == 'Firefox' …
结构分成多行可读性更高。
但 switch
结构更清晰明了。