JavaScript速記技巧:向著更清晰的代碼邁進
本文轉載自公眾號“讀芯術”(ID:AI_Discovery)。
無論是哪個編程語言的速記技巧,都有助于你編寫更好、更清晰的代碼。借助速記技巧,不僅可以提升代碼可讀性,還可以編寫更少代碼完成任務。下面是一些JavaScript的速記技巧。
1. 聲明變量
- //Longhand
- let x;
- let y = 20;
- //Shorthand
- let x, y = 20;
2. 給多個變量賦值
可以在一行代碼中給多個變量同時賦值。
- //Longhand
- let marks = 26;
- let result;
- if(marks >= 30){
- result = 'Pass';
- }else{
- result = 'Fail';
- }
- //Shorthand
- let result = marks >= 30 ? 'Pass' : 'Fail';
3. 三元運算符
使用三元運算符(條件),五行代碼可以簡化為一行。
- //Longhand
- let imagePath;
- let path = getImagePath();
- if(path !== null && path !== undefined && path !== '') {
- imagePath = path;
- } else {
- imagePath = 'default.jpg';
- }
- //Shorthand
- let imagePath = getImagePath() || 'default.jpg';
4. 分配默認值
我們可以使用OR(||)短路評估為變量指定一個默認值,以防期望值為空。
- //Longhand
- let imagePath;
- let path = getImagePath();
- if(path !== null && path !== undefined && path !== '') {
- imagePath = path;
- } else {
- imagePath = 'default.jpg';
- }
- //Shorthand
- let imagePath = getImagePath() || 'default.jpg';
5. AND(&&)短路評估
如需只在變量為真的情況下調用一個函數,則可使用AND(&&)短路評估在一行內完成。
- //Longhand
- if (isLoggedin) {
- goToHomepage();
- }
- //Shorthand
- isLoggedin && goToHomepage();
速記寫法這一行,只有在isLoggedin返回結果為真時,goToHomepage()才會執行。
6. 交換兩個變量
通常交換兩個變量需要借助第三個變量。然而通過數組析構賦值,可以輕松交換兩個變量。
- //Longhand
- console.log('You got a missed call from ' + number + ' at ' + time);
- //Shorthand
- console.log(`You got a missed call from ${number} at ${time}`);
7. 箭頭函數
- //Longhand
- function add(num1, num2) {
- return num1 + num2;
- }
- //Shorthand
- const add = (num1, num2) => num1 + num2;
8. 模板文字
我們通常使用“+”運算符連接字符串值和變量。有了ES6模板,我們可以通過一種更簡單的方式實現。
- //Longhand
- console.log('JavaScript, often abbreviated as JS, is a\n' + 'programming language thatconforms to the \n' +
- 'ECMAScript specification. JavaScript is high-level,\n' +
- 'often just-in-time compiled, and multi-paradigm.' ); //Shorthand
- console.log(`JavaScript, often abbreviated as JS, is a programming languagethat conforms to the ECMAScript specification. JavaScript is high-level, oftenjust-in-time compiled, and multi-paradigm.`);
9. 多行字符串
對于多行字符串,我們通常使用“+”運算符和換行轉義符(\n)進行連接。然而可以使用“`”簡化代碼。
- let firstname = 'Amitav';
- let lastname = 'Mishra'; //Longhand
- let obj = {firstname: firstname, lastname: lastname};
- //Shorthand
- let obj = {firstname, lastname};
10. 多重條件檢查
對于多值匹配,可以將所有的值放在數組中,并使用indexOf()或includes()方法。
- //Longhand
- if (value === 1 || value === 'one' || value === 2 || value === 'two') {
- // Execute some code
- }
- // Shorthand 1
- if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
- // Execute some code
- }// Shorthand 2
- if ([1, 'one', 2, 'two'].includes(value)) {
- // Execute some code
- }
11. 對象屬性分配
如果變量名和對象鍵名相同,可以只在對象文字中設置變量名,不用同時設置鍵和值。JavaScript會自動將鍵名設置為變量名,并將該值賦為變量值。
- let firstname = 'Amitav';
- let lastname = 'Mishra'; //Longhand
- let obj = {firstname: firstname, lastname: lastname};
- //Shorthand
- let obj = {firstname, lastname};
12. 字符串類型轉換為數字類型
有內置的方法,如parseInt 和parseFloat ,可用于將字符串轉換為數字。更簡單的方法是,在字符串值前加上一元運算符(+)。
- //Longhand
- let total = parseInt('453');
- let average = parseFloat('42.6');
- //Shorthand
- let total = +'453';
- let average = +'42.6';
13. 多次重復同一字符串
若要將字符串重復指定的次數,可以使用for 循環。但是使用repeat() 方法可以在一行中完成。
- //Longhand
- let str = '';
- for(let i = 0; i < 5; i ++) {
- str += 'Hello ';
- }
- console.log(str); // Hello Hello Hello Hello Hello
- // Shorthand
- 'Hello '.repeat(5)
小貼士:想通過給某人發100次“對不起”進行道歉?試試repeat()方法。如果你想在每次重復時另起一行,只需加上\n。
14. 指數冪
我們可以用Math.pow()方法求冪。然而用雙星號(**)有一個更短的語法。
- //Longhand
- const power = Math.pow(4, 3); // 64
- // Shorthand
- const power = 4**3; // 64
15. 按位雙非運算符
按位雙非運算符可以替代Math.floor()方法。
- //Longhand
- const floor = Math.floor(6.8); // 6
- // Shorthand
- const floor = ~~6.8; // 6
按位雙非運算符方法僅適用于32位整數,即(2**31)-1 = 2147483647。所以對于任何高于2147483647的數字,按位運算符(~~)都會給出錯誤的結果,所以在這種情況下建議使用Math.floor()。
16. 找出數組的最大值和最小值
可以使用for循環遍歷數組的每個值,從而找到最大值或最小值。也可以使用Array.reduce()方法來查找數組中的最大值和最小值。
但是使用擴展運算符則可在一行中完成。
- // Shorthand
- const arr = [2, 8, 15, 4];
- Math.max(...arr); // 15
- Math.min(...arr); // 2
17. For循環
為遍歷數組,通常使用的是傳統的for 循環,也可以使用for...of 循環進行遍歷。如需訪問每個值的索引,可以使用for...in循環。
- let arr = [10, 20, 30, 40]; //Longhand
- for (let i = 0; i < arr.length; i++) {
- console.log(arr[i]);
- } //Shorthand
- //for of loop
- for (const val of arr) {
- console.log(val);
- } //for in loop
- for (const index in arr) {
- console.log(arr[index]);
- }
使用for...in循環還可以遍歷對象屬性。
- let obj = {x: 20, y: 50};
- for (const key in obj) {
- console.log(obj[key]);
- }
18. 數組合并
- let arr1 = [20, 30]; //Longhand
- let arr2 = arr1.concat([60, 80]);
- // [20, 30, 60, 80]
- //Shorthand
- let arr2 = [...arr1, 60, 80];
- // [20, 30, 60, 80]
19. 多級對象的深度克隆
要深度克隆多級對象,可以遍歷每個屬性,并檢查當前屬性是否包含對象。如果是,則通過傳遞當前屬性值(即嵌套對象)對同一函數進行遞歸調用。也可以使用JSON.stringify()和JSON.parse()在一行中實現。
- let obj = {x: 20, y: {z: 30}};
- //Longhand
- const makeDeepClone = (obj) => {
- let newObject = {};
- Object.keys(obj).map(key => {
- if(typeof obj[key] === 'object'){
- newObject[key] =makeDeepClone(obj[key]);
- } else {
- newObject[key] = obj[key];
- }
- });
- return newObject;
- } const cloneObj = makeDeepClone(obj);
- //Shorthand
- const cloneObj = JSON.parse(JSON.stringify(obj));
如果對象屬性以函數作為值,則速記技巧(JSON.parse(JSON.stringify(obj)))無效。因為JSON.stringif作用于對象時,以函數作為值的屬性會從對象中移除。所以這種情況下,還是要用普通寫法。
20. 從字符串中獲取字符
- let str = 'jscurious.com'; //Longhand
- str.charAt(2); // c
- //Shorthand
- str[2]; // c
希望本文能讓你有所收獲。