js优化代码技巧

使用for循环时,缓存长度值

1
2
3
4
5
6
7
8
9
 // 通常用使用for循环遍历数组时,会采用以下写法:
for (var i = 0; i < arr.length; i++) {
// 具体操作
}

// 这段代码存在的问题在于,在循环的每个迭代步骤,都必须访问一次arr的长度。用len缓存长度值
for (var i = 0, len = arr.length; i < len; i++) {
// 具体操作
}

条件语句嵌套的优化

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
// before
if (color) {
if (color === 'black') {
BlackBackground();
} else if (color === 'red') {
RedBackground();
} else if (color === 'blue') {
BlueBackground();
} else if (color === 'green') {
GreenBackground();
} else {
YellowBackground();
}
}

// after
var colorObj = {
'black': printBlackBackground,
'red': printRedBackground,
'blue': printBlueBackground,
'green': printGreenBackground,
'yellow': printYellowBackground
};
if (color in colorObj) {
colorObj[color]();
}

三元、短路表达式用起来

1
2
3
4
5
6
7
8
// before
if (type === DEL) {
this.delateData(id)
} else {
this.addData(id)
}
// after
this[type === DEL ? 'delateData' : 'addData'](id)