10個JS最佳化小技巧
Write Less Do the Same
1。 if多條件判斷
// 冗餘
if
(
x
===
‘abc’
||
x
===
‘def’
||
x
===
‘ghi’
||
x
===
‘jkl’
)
{}
// 簡潔
if
([
‘abc’
,
‘def’
,
‘ghi’
,
‘jkl’
]。
includes
(
x
))
{}
2。 if。。。else。。。
// 冗餘
let
test
:
boolean
;
if
(
x
>
100
)
{
test
=
true
;
}
else
{
test
=
false
;
}
// 簡潔
let
test
=
x
>
10
;
3。 Null, Undefined, 空值檢查
// 冗餘
if
(
first
!==
null
||
first
!==
undefined
||
first
!==
‘’
)
{
let
second
=
first
;
}
// 簡潔
let
second
=
first
||
‘’
;
4。 foreach迴圈
// 冗餘
for
(
var
i
=
0
;
i
<
testData
。
length
;
i
++
)
// 簡潔
for
(
let
i
in
testData
)
// 或
for
(
let
i
of
testData
)
5。 函式條件呼叫
// 冗餘
function
test1
()
{
console
。
log
(
‘test1’
);
};
function
test2
()
{
console
。
log
(
‘test2’
);
};
var
test3
=
1
;
if
(
test3
==
1
)
{
test1
();
}
else
{
test2
();
}
// 簡單
(
test3
===
1
?
test1
:
test2
)();
6。 switch條件
// 冗餘
switch
(
data
)
{
case
1
:
test1
();
break
;
case
2
:
test2
();
break
;
case
3
:
test
();
break
;
// so on。。。
}
// 簡潔
var
data
=
{
1
:
test1
,
2
:
test2
,
3
:
test
};
data
[
anything
]
&&
data
[
anything
]();
7。 多行字串
// 冗餘
const
data
=
‘abc abc abc abc abc abc\n\t’
+
‘test test,test test test test\n\t’
// 簡潔
const
data
=
`abc abc abc abc abc abc
test test,test test test test`
8。 隱式返回
// 冗餘
function
getArea
(
diameter
)
{
return
Math
。
PI
*
diameter
}
// 簡潔
getArea
=
diameter
=>
(
Math
。
PI
*
diameter
;
)
9。 重複字串多次
// 冗餘
let
test
=
‘’
;
for
(
let
i
=
0
;
i
<
5
;
i
++
)
{
test
+=
‘test ’
;
}
// 簡潔
‘test ’
。
repeat
(
5
);
10。 冪乘
// 冗餘
Math。pow(2,3);
// 簡潔而
2**3 // 8
參考
原文 -
https://
dev。to/blessingartcreat
or/17-javascript-optimization-tips-3gil
文章首發 -
https://
github。com/reng99/blogs
/issues/82
更多內容 -
https://
github。com/reng99/blogs