[點晴永久免費OA]Javascript常用的16個簡寫小技巧 開發效率直接翻倍
當前位置:點晴教程→點晴OA辦公管理信息系統
→『 經驗分享&問題答疑 』
JavaScript 是一門強大且靈活的語言,擁有豐富的特性和語法糖。分享下 16 個最常用的 JavaScript 的簡寫技巧,掌握它們可以讓我們編寫出更簡潔、更優雅的代碼,并顯著提升開發效率。 1. 聲明多個變量 常規寫法: let a; let b; let c;
簡寫: let a, b, c;
2. If - Else 簡寫 常規 if - else : let num = 10; let result; if (num > 5) { result = '大于5'; } else { result = '小于等于5'; }
三元運算符簡寫: let num = 10; let result = num > 5? '大于5' : '小于等于5';
3. && 短路求值 常規寫法: let message; let condition = true; if (condition) { message = '條件為真'; }
簡寫: let condition = true; let message = condition && '條件為真';
4. || 短路求值 常規寫法: let value; let someValue = null; if (someValue) { value = someValue; } else { value = '默認值'; }
簡寫: let someValue = null; let value = someValue || '默認值';
5. 對象屬性簡寫 常規寫法: let name = 'John'; let age = 30; let person = { name: name, age: age };
簡寫: let name = 'John'; let age = 30; let person = { name, age };
6. 對象方法簡寫 常規寫法: let obj = { method: function () { console.log('方法執行'); } };
簡寫: let obj = { method() { console.log('方法執行'); } };
7. 箭頭函數 常規函數: function add(a, b) { return a + b; }
箭頭函數簡寫: const add = (a, b) => a + b;
8. 數組解構賦值 常規寫法: let arr = [1, 2]; let a = arr[0]; let b = arr[1];
簡寫: javascript let [a, b] = [1, 2];
9. 對象解構賦值 常規寫法: let person = { name: 'John', age: 30 }; let name = person.name; let age = person.age;
簡寫: let { name, age } = { name: 'John', age: 30 };
10. 擴展運算符(數組) 合并數組常規寫法: let arr1 = [1, 2]; let arr2 = [3, 4]; let combined = arr1.concat(arr2);
擴展運算符簡寫: let arr1 = [1, 2]; let arr2 = [3, 4]; let combined = [...arr1,...arr2];
11. 擴展運算符(對象) 合并對象常規寫法: let obj1 = { a: 1 }; let obj2 = { b: 2 }; let merged = Object.assign({}, obj1, obj2);
擴展運算符簡寫: let obj1 = { a: 1 }; let obj2 = { b: 2 }; let merged = {...obj1,...obj2 };
12. for...of 循環遍歷數組 for 循環常規寫法: let arr = [1, 2, 3]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
for...of 簡寫: let arr = [1, 2, 3]; for (let num of arr) { console.log(num); }
13. 數組 map 方法創建新數組 常規 for 循環創建新數組: let arr = [1, 2, 3]; let newArr = []; for (let i = 0; i < arr.length; i++) { newArr.push(arr[i] * 2); }
map 方法簡寫: let arr = [1, 2, 3]; let newArr = arr.map(num => num * 2);
14. 數組 filter 方法過濾數組 常規 for 循環過濾數組: let arr = [1, 2, 3, 4, 5]; let filteredArr = []; for (let i = 0; i < arr.length; i++) { if (arr[i] > 3) { filteredArr.push(arr[i]); } }
filter 方法簡寫: let arr = [1, 2, 3, 4, 5]; let filteredArr = arr.filter(num => num > 3);
15. 指數運算 常規寫法: let result = Math.pow(2, 3);
指數運算符簡寫: let result = 2 ** 3;
16. 模板字面量 常規字符串拼接: let name = 'John'; let greeting = 'Hello, ' + name + '!';
模板字面量簡寫: let name = 'John'; let greeting = `Hello, ${name}!`; 該文章在 2025/1/7 12:33:05 編輯過 |
關鍵字查詢
相關文章
正在查詢... |