我們經常會寫一些 JavaScript 代碼,但是如何寫出幹淨又易維護的代碼呢?本文将講解 17 個 JavaScript 代碼的技術幫助你提高程式設計水準,此外,本文可以幫助您為 2021 年的 JavaScript 面試做好準備。
(注意,我會把差的代碼放在上面用注釋的,好的代碼放在下面用
//longhand
注釋的,以作比較)
//shorthand
1. If 多個條件的時候
有時候你會經常判斷一個變量是否等于多個值的情況:
//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
//logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
//logic
}
2. If true … else
if else? 還不如用三元運算符
// Longhand
let test: boolean;
if (x > 100) {
test = true;
} else {
test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can simply use
let test = x > 10;
console.log(test);
三元運算符還可以嵌套,像下面這樣:
let x = 300,
let test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"
但是不建議嵌套太多層的。
3. Null, Undefined, 空檢查
前面有空值,如何判斷?
// Longhand
if (first !== null || first !== undefined || first !== '') {
let second = first;
}
// Shorthand
let second = first|| '';
4. Null Value 檢查與配置設定預設值
let first = null,
let second = first || '';
console.log("null check", test2); // output will be ""
5. Undefined 檢查與配置設定預設值
let first= undefined,
let second = first || '';
console.log("undefined check", test2); // output will be ""
6.foreach 循環
如何更好的疊代?
// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) 或 for (let i of testData)
上面
let i in
或
let i of
是比較好的方式,
或者下面這樣:使用
forEach
function testData(element, index, array) {
console.log('test[' + index + '] = ' + element);
}
[11, 24, 32].forEach(testData);
// prints: test[0] = 11, test[1] = 24, test[2] = 32
7. 比較傳回
在 return 語句中使用比較将避免我們的 5 行代碼,并将它們減少到 1 行。
// Longhand
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe('test');
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
}
// Shorthand
function checkReturn() {
return test || callMe('test');
}
8. 函數調用簡單的方式
用三元運算符解決函數調用
// Longhand
function test1() {
console.log('test1');
};
function test2() {
console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
test1();
} else {
test2();
}
// Shorthand
(test3 === 1? test1:test2)();
9. Switch
switch 有時候太長?看看能不能優化
// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[anything] && data[anything]();
10. 多行字元串速記
字元串多行時,如何更好的處理?用
+
号?
//longhand
const data = 'abc abc abc abc abc abc\n\t'
+ 'test test,test test test test\n\t'
//shorthand
const data = `abc abc abc abc abc abc
test test,test test test test`
11.Implicit Return Shorthand
當用剪頭函數時,有個隐式傳回,注意括号。
Longhand:
//longhand
function getArea(diameter) {
return Math.PI * diameter
}
//shorthand
getArea = diameter => (
Math.PI * diameter;
)
12.Lookup Conditions Shorthand
如果我們有代碼來檢查類型,并且基于類型需要調用不同的方法,我們可以選擇使用多個 else ifs 或進行切換,但是如果我們有比這更好的方式呢?
// Longhand
if (type === 'test1') {
test1();
}
else if (type === 'test2') {
test2();
}
else if (type === 'test3') {
test3();
}
else if (type === 'test4') {
test4();
} else {
throw new Error('Invalid value ' + type);
}
// Shorthand
var types = {
test1: test1,
test2: test2,
test3: test3,
test4: test4
};
var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();
13.Object.entries()
此功能有助于将對象轉換為對象數組。
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };
const arr = Object.entries(data);
console.log(arr);
/** Output:
[ [ 'test1', 'abc' ],
[ 'test2', 'cde' ],
[ 'test3', 'efg' ]
]
**/
14. Object.values()
這也是 ES8 中引入的一項新功能,它執行與 Object.Entry () 類似的功能,但沒有關鍵部分:
const data = { test1: 'abc', test2: 'cde' };
const arr = Object.values(data);
console.log(arr);
/** Output:
[ 'abc', 'cde']
**/
15. 多次重複字元串
為了一次又一次地重複相同的字元,我們可以使用 for 循環并将它們添加到同一個循環中,但是如果我們有一個速記呢?
//longhand
let test = '';
for(let i = 0; i < 5; i ++) {
test += 'test ';
}
console.log(str); // test test test test test
//shorthand
'test '.repeat(5);
16. 指數幂函數
數學指數幂函數的速記:
//longhand
Math.pow(2,3); // 8
//shorthand
2**3 // 8
17. 數字分隔符
現在,您隻需使用 _ 即可輕松分隔數字。
//old syntax
let number = 98234567
//new syntax
let number = 98_234_567
結論
我們在編寫代碼的過程中多思考,多記錄,看看哪種是最好,又是最短的方式,這樣有助于提高程式設計水準。
其他精彩文章
- 2021 年你應該嘗試的 8 個 React 庫
- 使用 Node, Sequelize, Postgres 和 Docker 搭建 CURD API【譯】
- 5 個你會在 2021 年的 React 項目中用到的庫
- 【分享】每個 Web 開發者在 2021 年必須擁有 15 個 VSCode 擴充
- 【分享】73 個提高生産力的很棒的 NPM 包【譯】