日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
JavaScript速記技巧:向著更清晰的代碼邁進

本文轉(zhuǎn)載自公眾號“讀芯術”(ID:AI_Discovery)。

無論是哪個編程語言的速記技巧,都有助于你編寫更好、更清晰的代碼。借助速記技巧,不僅可以提升代碼可讀性,還可以編寫更少代碼完成任務。下面是一些JavaScript的速記技巧。

1. 聲明變量

 
 
 
 
  1. //Longhand  
  2. let x;  
  3. let y = 20;  
  4. //Shorthand  
  5. let x, y = 20; 

2. 給多個變量賦值

可以在一行代碼中給多個變量同時賦值。

 
 
 
 
  1. //Longhand  
  2. let marks = 26;  
  3. let result;  
  4. if(marks >= 30){ 
  5.  result = 'Pass';  
  6. }else{  
  7.  result = 'Fail';  
  8. }  
  9. //Shorthand  
  10. let result = marks >= 30 ? 'Pass' : 'Fail'; 

3. 三元運算符

使用三元運算符(條件),五行代碼可以簡化為一行。

 
 
 
 
  1. //Longhand  
  2. let imagePath;  
  3. let path = getImagePath();  
  4. if(path !== null && path !== undefined && path !== '') {  
  5.   imagePath = path;  
  6. } else {  
  7.   imagePath = 'default.jpg';  
  8. }  
  9. //Shorthand  
  10. let imagePath = getImagePath() || 'default.jpg'; 

4. 分配默認值

我們可以使用OR(||)短路評估為變量指定一個默認值,以防期望值為空。

 
 
 
 
  1. //Longhand  
  2. let imagePath;  
  3. let path = getImagePath();  
  4. if(path !== null && path !== undefined && path !== '') {  
  5.   imagePath = path;  
  6. } else {  
  7.   imagePath = 'default.jpg';  
  8. }  
  9. //Shorthand  
  10. let imagePath = getImagePath() || 'default.jpg'; 

5. AND(&&)短路評估

如需只在變量為真的情況下調(diào)用一個函數(shù),則可使用AND(&&)短路評估在一行內(nèi)完成。

 
 
 
 
  1. //Longhand  
  2. if (isLoggedin) { 
  3.  goToHomepage();  
  4. }  
  5. //Shorthand  
  6. isLoggedin && goToHomepage(); 

速記寫法這一行,只有在isLoggedin返回結果為真時,goToHomepage()才會執(zhí)行。

6. 交換兩個變量

通常交換兩個變量需要借助第三個變量。然而通過數(shù)組析構賦值,可以輕松交換兩個變量。

 
 
 
 
  1. //Longhand  
  2. console.log('You got a missed call from ' + number + ' at ' + time);  
  3. //Shorthand  
  4. console.log(`You got a missed call from ${number} at ${time}`); 

7. 箭頭函數(shù)

 
 
 
 
  1. //Longhand  
  2. function add(num1, num2) {  
  3.    return num1 + num2;  
  4. }  
  5. //Shorthand  
  6. const add = (num1, num2) => num1 + num2; 

8. 模板文字

我們通常使用“+”運算符連接字符串值和變量。有了ES6模板,我們可以通過一種更簡單的方式實現(xiàn)。

 
 
 
 
  1. //Longhand  
  2. console.log('JavaScript, often abbreviated as JS, is a\n' +             'programming language thatconforms to the \n' +  
  3. 'ECMAScript specification. JavaScript is high-level,\n' +  
  4. 'often just-in-time compiled, and multi-paradigm.' ); //Shorthand  
  5. 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. 多行字符串

對于多行字符串,我們通常使用“+”運算符和換行轉(zhuǎn)義符(\n)進行連接。然而可以使用“`”簡化代碼。

 
 
 
 
  1. let firstname = 'Amitav';  
  2. let lastname = 'Mishra'; //Longhand  
  3. let obj = {firstname: firstname, lastname: lastname};  
  4. //Shorthand  
  5. let obj = {firstname, lastname}; 

10. 多重條件檢查

對于多值匹配,可以將所有的值放在數(shù)組中,并使用indexOf()或includes()方法。

 
 
 
 
  1. //Longhand  
  2. if (value === 1 || value === 'one' || value === 2 || value === 'two') {  
  3.      // Execute some code  
  4. }  
  5. // Shorthand 1 
  6. if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {  
  7.     // Execute some code  
  8. }// Shorthand 2 
  9. if ([1, 'one', 2, 'two'].includes(value)) {  
  10.     // Execute some code  

11. 對象屬性分配

如果變量名和對象鍵名相同,可以只在對象文字中設置變量名,不用同時設置鍵和值。JavaScript會自動將鍵名設置為變量名,并將該值賦為變量值。

 
 
 
 
  1. let firstname = 'Amitav';  
  2. let lastname = 'Mishra'; //Longhand  
  3. let obj = {firstname: firstname, lastname: lastname};  
  4. //Shorthand  
  5. let obj = {firstname, lastname}; 

12. 字符串類型轉(zhuǎn)換為數(shù)字類型

有內(nèi)置的方法,如parseInt 和parseFloat ,可用于將字符串轉(zhuǎn)換為數(shù)字。更簡單的方法是,在字符串值前加上一元運算符(+)。

 
 
 
 
  1. //Longhand  
  2. let total = parseInt('453');  
  3. let average = parseFloat('42.6');  
  4. //Shorthand  
  5. let total = +'453';  
  6. let average = +'42.6'; 

13. 多次重復同一字符串

若要將字符串重復指定的次數(shù),可以使用for 循環(huán)。但是使用repeat() 方法可以在一行中完成。

 
 
 
 
  1. //Longhand  
  2. let str = '';  
  3. for(let i = 0; i < 5; i ++) {  
  4.   str += 'Hello ';  
  5. }  
  6. console.log(str); // Hello Hello Hello Hello Hello  
  7. // Shorthand  
  8. 'Hello '.repeat(5) 

小貼士:想通過給某人發(fā)100次“對不起”進行道歉?試試repeat()方法。如果你想在每次重復時另起一行,只需加上\n。

14. 指數(shù)冪

我們可以用Math.pow()方法求冪。然而用雙星號(**)有一個更短的語法。

 
 
 
 
  1. //Longhand  
  2. const power = Math.pow(4, 3); // 64  
  3. // Shorthand  
  4. const power = 4**3; // 64 

15. 按位雙非運算符

按位雙非運算符可以替代Math.floor()方法。

 
 
 
 
  1. //Longhand  
  2. const floor = Math.floor(6.8); // 6  
  3. // Shorthand  
  4. const floor = ~~6.8; // 6 

按位雙非運算符方法僅適用于32位整數(shù),即(2**31)-1 = 2147483647。所以對于任何高于2147483647的數(shù)字,按位運算符(~~)都會給出錯誤的結果,所以在這種情況下建議使用Math.floor()。

16. 找出數(shù)組的最大值和最小值

可以使用for循環(huán)遍歷數(shù)組的每個值,從而找到最大值或最小值。也可以使用Array.reduce()方法來查找數(shù)組中的最大值和最小值。

但是使用擴展運算符則可在一行中完成。

 
 
 
 
  1. // Shorthand  
  2. const arr = [2, 8, 15, 4];  
  3. Math.max(...arr); // 15  
  4. Math.min(...arr); // 2 

17. For循環(huán)

為遍歷數(shù)組,通常使用的是傳統(tǒng)的for 循環(huán),也可以使用for...of 循環(huán)進行遍歷。如需訪問每個值的索引,可以使用for...in循環(huán)。

 
 
 
 
  1. let arr = [10, 20, 30, 40]; //Longhand  
  2. for (let i = 0; i < arr.length; i++) {  
  3.   console.log(arr[i]);  
  4. } //Shorthand  
  5. //for of loop  
  6. for (const val of arr) {  
  7.   console.log(val);  
  8. } //for in loop  
  9. for (const index in arr) {  
  10.   console.log(arr[index]);  

使用for...in循環(huán)還可以遍歷對象屬性。

 
 
 
 
  1. let obj = {x: 20, y: 50};  
  2. for (const key in obj) {  
  3.   console.log(obj[key]);  

18. 數(shù)組合并

 
 
 
 
  1. let arr1 = [20, 30]; //Longhand  
  2. let arr2 = arr1.concat([60, 80]);  
  3. // [20, 30, 60, 80]  
  4. //Shorthand  
  5. let arr2 = [...arr1, 60, 80];  
  6. // [20, 30, 60, 80] 

19. 多級對象的深度克隆

要深度克隆多級對象,可以遍歷每個屬性,并檢查當前屬性是否包含對象。如果是,則通過傳遞當前屬性值(即嵌套對象)對同一函數(shù)進行遞歸調(diào)用。也可以使用JSON.stringify()和JSON.parse()在一行中實現(xiàn)。

 
 
 
 
  1. let obj = {x: 20, y: {z: 30}};  
  2. //Longhand  
  3. const makeDeepClone = (obj) => {  
  4.   let newObject = {};  
  5.   Object.keys(obj).map(key => {  
  6.     if(typeof obj[key] === 'object'){  
  7.       newObject[key] =makeDeepClone(obj[key]);  
  8.     } else {  
  9.       newObject[key] = obj[key];  
  10.     }  
  11.   });  
  12.  return newObject;  
  13. } const cloneObj = makeDeepClone(obj);  
  14. //Shorthand  
  15. const cloneObj = JSON.parse(JSON.stringify(obj)); 

如果對象屬性以函數(shù)作為值,則速記技巧(JSON.parse(JSON.stringify(obj)))無效。因為JSON.stringif作用于對象時,以函數(shù)作為值的屬性會從對象中移除。所以這種情況下,還是要用普通寫法。

20. 從字符串中獲取字符

 
 
 
 
  1. let str = 'jscurious.com'; //Longhand  
  2. str.charAt(2); // c  
  3. //Shorthand  
  4. str[2]; // c 

希望本文能讓你有所收獲。


分享名稱:JavaScript速記技巧:向著更清晰的代碼邁進
轉(zhuǎn)載來源:http://m.5511xx.com/article/cdgcjco.html