JavaScript 的簡短寫法


在網上遊網時發現原來 JavaScript 是屬於函式語言?所以在 if, else 中失去了效率,變相就有了以下的取代方法,
整理了一下代碼如下:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 先定義要用到的變量
var a = 1, b = 0 , c = "";

/* 寫法一 */
// 簡寫:
a && (c += "OK");

// 正寫:
if (a) {
c += "OK";
}

/* 寫法二 */
// 簡寫:
b || (b = 2);

// 正寫:
if (!b) {
b = 2;
}

/* 寫法三 */
// 簡寫:
a ? ( (c = "yes"), (b = 1) ) : ( (c = "no"), (b = 2) );

// 正寫
if (a) {
c = "yes";
b = 1;
}else{
c = "no";
b = 2;
}

/* 寫法四 */
// 簡寫 (1):
(a == window.getElementById("c")) && (a.style.display = "none");

// 簡寫 (2):
(a == window.getElementById("c")) ? a.style.display = "none" : "";

// 正寫:
if (a == window.getElementById("c")) {
a.style.display = "none";
}

/* 寫法五 */
// 簡寫
return a.nodeType != 3
? a.tagName
: a.setIntval
? "window"
: "other"

// 正寫
if (a.nodeType != 3) {
return a.tageName;
}else if (a.setIntval) {
return "window";
}else{
return "other";
}