20 个超级有⽤的 JavaScript 技巧
1.
多条件 if 语句
将多个值放⼊⼀个数组中,然后调⽤该数组的 include ⽅法。
1
// bad
2
if
(x ===
"abc"
|| x ===
"def"
|| x ===
"ghi"
|| x ===
"jkl"
) {
3
//logic
4
}
5
6
// better
7
if
([
"abc"
,
"def"
,
"ghi"
,
"jkl"
].
includes
(x)) {
8
//logic
9
}
10
2.
简化 if true...else 条件表达式
1
// bad
2
let
test
: boolean;
3
if
(x >
100
) {
4
test =
true
;
5
}
else
{
6
test =
false
;
7
}
8
9
// better
10
let
test = x >
10
?
true
:
false
;
11
12
//or let test = x > 10;
13
14
console
.
log
(test);
15
16
3.
假值(undefined, null, 0, false, NaN, empty string)检
查
当我们创建⼀个新变量时,有时我们想检查引⽤的变量是否是⼀个假值,例如 null 或 undefined 或空
字符串。JavaScript 确实为这种检查提供了⼀个很好的快捷⽅式⸺逻辑 OR 运算符 (||)
|| 仅当左侧为空或 NaN 或 null 或 undefined 或 false 时,如果左侧操作数为假,则将返回右侧操作
数,逻辑或运算符 ( || ) 将返回右侧的值。
1
// bad
2
if
(test1 !==
null
|| test1 !==
undefined
|| test1 !==
""
) {
3
let
test2 = test1;
4
}
5
6
//
7
better
8
let
test2 = test1 ||
""
;
9
10
// bad
11
if
(test1 ===
true
) or
if
(test1 !==
""
) or
if
(test1 !==
null
)
12
13
// better
14
if
(test1){
15
// do some
16
}
else
{
17
// do other
18
}
19
20
//Note: If test1 has a value, the logic after if will be executed. //This
operator is mainly used for null, undefined, and empty string checks.
21
22
4.
null/undefined 检查和默认赋值
1
//null checking and default assignment
2
3
let
test1 =
null
;
4
let
test2 = test1 ??
""
;
5
6
console
.
log
(
"null check"
, test2);
// output empty string ""
7
8
//undefined checking and default assignment
9
10
const
test =
undefined
??
"default"
;
11
console
.
log
(test);
// expected output: "default"
12
13
5.
获取列表中的最后⼀项
在其他语⾔中,此功能被制成可以在数组上调⽤的⽅法或函数,但在 JavaScript 中,你必须⾃⼰做⼀
些⼯作。
1
let
array = [
0
,
1
,
2
,
3
,
4
,
5
,
6
,
7
];
2
3
console
.
log
(array.
slice
(-
1
)) >>> [
7
];
4
console
.
log
(array.
slice
(-
2
)) >>> [
6
,
7
];
5
console
.
log
(array.
slice
(-
3
)) >>> [
5
,
6
,
7
];
6
7
function
lastItem
(list) {
8
if
(
Array
.
isArray
(list)) {
9
return
list.
slice
(-
1
)[
0
];
10
}
11
if
(list
instanceof
Set
) {
12
return
Array
.
from
(list).
slice
(-
1
)[
0
];
13
}
14
if
(list
instanceof
Map
) {
15
return
Array
.
from
(list.
values
()).
slice
(-
1
)[
0
];
16
}
17
}
18
19
6.
⽐较后返回
1
let
test;
2
function
checkReturn
() {
3
if
(!(test ===
undefined
)) {
4
return
test;
5
}
else
{
6
return
callMe
(
"test"
);
7
}
8
}
9
10
// better
11
function
checkReturn
() {
12
return
test ??
callMe
(
"test"
);
13
}
14
15
7.
使⽤可选的链接运算符 -?。
? 也称为链判断运算,它允许开发⼈员读取深度嵌套在对象链中的属性值,⽽⽆需验证每个引⽤,当引
⽤为空时,表达式停⽌计算并返回 undefined。
1
const
travelPlans = {
2
destination
:
"DC"
,
3
monday
: {
4
location
:
"National Mall"
,
5
budget
:
200
, },
6
};
7
8
// bad
9
const
res = travelPlans && travelPlans.tuesday && travelPlans.tuesday.location
&& travelPlans.tuesday.location.href;
10
console
.
log
(res);
// Result: undefined
11
12
// better
13
const
res1 = travelPlans?.tuesday?.location?.href;
14
console
.
log
(res1);
// Result: undefined
15
16
8.
多个条件的 && 运算符
要仅在变量为真时调⽤函数,请使⽤ && 运算符。
1
// bad
2
if
(test) {
3
callMethod
();
4
}
5
6
// better
7
test &&
callMethod
();
当你想在 React 中有条件地渲染组件时,这对于使⽤ (&&) 进⾏短路很有⽤。例如:
1
<div> {
this
.state.isLoading && <
Loading
/>} </div>
9.
开关简化
我们可以将条件存储在键值对象中,并根据条件调⽤它们。
1
switch
(data) {
2
case
1
:
3
test1
();
4
break
;
5
case
2
:
6
test2
();
7
break
;
8
case
3
:
9
test
();
10
break
;
// And so on...
11
}
12
13
// better
14
var
data = {
15
1
: test1,
16
2
: test2,
17
3
: test,
18
};
19
// If type exists in data, execute the corresponding function
20
data[type] && data[type]();
21
22
10.
默认参数值
1
function
add
(test1, test2) {
2
if
(test1 ===
undefined
)
3
test1 =
1
;
4
if
(test2 ===
undefined
)
5
test2 =
2
;
6
return
test1 + test2;}
7
8
// better
9
add = (test1 =
1
, test2 =
2
) => test1 + test2;
add
();
//output: 3
10
11.
条件查找简化
如果我们想根据不同的类型调⽤不同的⽅法,我们可以使⽤多个 else if 语句或开关,但是还有⽐这更
好的简化技巧吗?其实和之前的switch简化是⼀样的。
1
// bad
2
if
(type ===
"test1"
) {
3
test1
();
4
}
else if
(type ===
"test2"
) {
5
test2
();}
else if
(type ===
"test3"
) {
6
test3
();}
else if
(type ===
"test4"
) {
7
test4
();}
else
{
8
throw new
Error
(
"Invalid value "
+ type);
9
}
10
11
// better
12
var
types = { test1, test2, test3, test4,};types[type] && types[type]();
13
14
12.
对象属性赋值
1
let
test1 =
"a"
;
let
test2 =
"b"
;
2
// bad
3
let
obj = {
test1
: test1,
test2
: test2 }
;
4
5
// better
6
let
obj = { test1, test2 }
;
13.
解构赋值
1
// bad
2
const
test1 =
this
.data.test1;
3
const
test2 =
this
.data.test2;
4
const
test3 =
this
.data.test3;
5
6
// better
7
const
{ test1, test2, test3 } =
this
.data;
8
9
14.
模板字符串
如果你厌倦了使⽤ + 将多个变量连接成⼀个字符串,这个简化技巧会让你头疼。
1
// bad
2
const
welcome =
"Hi "
+ test1 +
" "
+ test2 +
"."
;
3
4
// better
5
const
welcome =
`Hi
${test1} ${test2}
`
;
15.
跨越字符串
1
// bad
2
const
data =
3
"hello maxwell this is a test\n\t"
+
"test test,test test test
test\n\t"
;
4
5
// better
6
const
data =
`hello maxwell this is a test
7
test test,test test test test`
;
8
9
16.
indexOf的按位化简
在数组中查找某个值时,我们可以使⽤ indexOf() ⽅法。但是还有更好的⽅法,我们来看这个例⼦。
1
// bad
2
if
(arr.
indexOf
(item) > -
1
) {
// item found
}
if
(arr.
indexOf
(item) === -
1
) {
// item not found
}
// better
if
(~arr.
indexOf
(item)) {
// item found
}
if
(!~arr.
indexOf
(item)) {
// item not found
}
//The bitwise (~) operator will return true (except for -1), //the reverse
operation only requires !~. Alternatively, the includes() function can be used.
if
(arr.
includes
(item)) {
// true if the item found
}
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
17.
将字符串转换为数字
有诸如 parseInt 和 parseFloat 等内置⽅法可⽤于将字符串转换为数字。我们也可以简单地通过在字符
串前⾯提供⼀元运算符 (+) 来做到这⼀点。
// bad
let
total =
parseInt
(
"583"
);
let
average =
parseFloat
(
"32.5"
);
// better
let
total = +
"583"
;
let
average = +
"32.5"
;
1
2
3
4
5
6
7
18.
按顺序执⾏ Promise
如果你有⼀堆异步或普通函数都返回要求你⼀个⼀个执⾏它们的Promise怎么办?
async function
getData
() {
const
promises = [
fetch
(
"url1"
),
fetch
(
"url2"
),
fetch
(
"url3"
),
fetch
(
"url4"
)];
1
2
3
for
(
const
item
of
promises) {
4
// Print out the promise
5
console
.
log
(item);
6
}
7
8
// better
9
for await
(
const
item
of
promises) {
10
// Print out the results of the request
11
console
.
log
(item);
12
}
13
}
14
15
等待所有Promiae完成。
Promise.allSettled() ⽅法接受⼀组 Promise 实例作为参数,包装到⼀个新的 Promise 实例中。在所
有这些参数实例都返回结果(已完成或已拒绝)之前,包装器实例不会结束。
有时候,我们并不关⼼异步请求的结果,我们只关⼼是否所有请求都结束了。这时候,
Promise.allSettled() ⽅法就⾮常有⽤了。
1
const
promises = [
fetch
(
"index.html"
),
fetch
(
"https://does-not-exist/"
)];
2
3
const
results =
await
Promise
.
allSettled
(promises);
4
5
// Filter out successful requests
6
const
successfulPromises = results.
filter
((p) => p.status ===
"fulfilled"
);
7
8
// Filter out failed requests and output the reason
9
const
errors = results.
filter
((p) => p.status ===
"rejected"
).
map
((p) =>
p.reason);
10
11
19.
交换数组元素的位置
1
// bad
2
const
swapWay
= (arr, i, j) => {
const
newArr = [...arr];
3
4
let
temp = newArr[i];
5
newArr[i] = list[j]; newArr[j] = temp;
6
7
return
newArr;};
8
9
//Since ES6, swapping values from different locations in an array has become
much easier
10
11
// better
12
const
swapWay
= (arr, i, j) => {
const
newArr = [...arr];
13
14
const
[newArr[j],newArr[i]] = [newArr[i],newArr[j]];
15
16
return
newArr;};
17
18
20.
带范围的随机数⽣成器
有时你需要⽣成随机数,但⼜希望数字在⼀定范围内,则可以使⽤此⼯具。
1
function
randomNumber
(max =
1
, min =
0
) {
2
if
(min >= max) {
3
return
max;
4
}
5
return
Math
.
floor
(
Math
.
random
() * (max - min) + min);
6
}
7
8