自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

20個常用的JavaScript簡寫技巧

開發(fā) 前端
任何編程語言的簡寫技巧都能夠幫助你編寫更簡練的代碼,讓你用更少的代碼實現(xiàn)你的目標。讓我們一個個來看看 JavaScript 的簡寫技巧吧。

 任何編程語言的簡寫技巧都能夠幫助你編寫更簡練的代碼,讓你用更少的代碼實現(xiàn)你的目標。讓我們一個個來看看 JavaScript 的簡寫技巧吧。

1. 聲明變量

 

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

 

2. 給多個變量賦值

我們可以使用數(shù)組解構來在一行中給多個變量賦值。

 

  1. //Longhand 
  2. let a, b, c; 
  3. a = 5; 
  4. b = 8; 
  5. c = 12; 
  6.  
  7. //Shorthand 
  8. let [a, b, c] = [5, 8, 12]; 

 

3. 三元運算符

我們可以使用三元(條件)運算符在這里節(jié)省 5 行代碼。

 

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

 

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. //Shorthand 
  9. let imagePath = getImagePath() || 'default.jpg'

 

5. 與 (&&) 短路運算

如果你只有當某個變量為 true 時調用一個函數(shù),那么你可以使用與 (&&)短路形式書寫。

 

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

 

當你在 React 中想要有條件地渲染某個組件時,這個與 (&&)短路寫法比較有用。例如:

 

  1. <div> { this.state.isLoading && <Loading /> } </div> 

 

6. 交換兩個變量

為了交換兩個變量,我們通常使用第三個變量。我們可以使用數(shù)組解構賦值來交換兩個變量。

 

  1. let x = 'Hello', y = 55; 
  2. //Longhand 
  3. const temp = x; 
  4. x = y; 
  5. y = temp
  6. //Shorthand 
  7. [x, y] = [y, x]; 

 

7. 箭頭函數(shù)

 

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

 

參考:JavaScript Arrow function

https://jscurious.com/javascript-arrow-function/

8. 模板字符串

我們一般使用 + 運算符來連接字符串變量。使用 ES6 的模板字符串,我們可以用一種更簡單的方法實現(xiàn)這一點。

 

  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}`); 

 

9. 多行字符串

對于多行字符串,我們一般使用 + 運算符以及一個新行轉義字符(\n)。我們可以使用 (`) 以一種更簡單的方式實現(xiàn)。

 

  1. //Longhand 
  2. console.log('JavaScript, often abbreviated as JS, is a\n' + 'programming language that conforms to the \n' + 
  3. 'ECMAScript specification. JavaScript is high-level,\n' + 
  4. 'often just-in-time compiled, and multi-paradigm.' ); 
  5. //Shorthand 
  6. console.log(`JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.`); 

 

10. 多條件檢查

對于多個值匹配,我們可以將所有的值放到數(shù)組中,然后使用indexOf()或includes()方法。

 

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

 

11. 對象屬性復制

如果變量名和對象的屬性名相同,那么我們只需要在對象語句中聲明變量名,而不是同時聲明鍵和值。JavaScript 會自動將鍵作為變量的名,將值作為變量的值。

 

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

 

12. 字符串轉成數(shù)字

有一些內置的方法,例如parseInt和parseFloat可以用來將字符串轉為數(shù)字。我們還可以簡單地在字符串前提供一個一元運算符 (+) 來實現(xiàn)這一點。

 

  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. 重復一個字符串多次為了重復一個字符串 N 次,你可以使用for循環(huán)。但是使用repeat()方法,我們可以一行代碼就搞定。

 

  1. //Longhand 
  2. let str = ''
  3. for(let i = 0; i < 5; i ++) { 
  4.   str += 'Hello '
  5. console.log(str); // Hello Hello Hello Hello Hello 
  6. // Shorthand 
  7. 'Hello '.repeat(5);提示: 想要給某人發(fā) 100 遍“sorry”來道歉嗎?用 repeat() 方法試試吧。如果你想要每次在新的一行重復字符串,可以在字符串后面加一個 \n 。 
  8. 'sorry\n'.repeat(100); 

 

14. 指數(shù)冪

我們可以使用Math.pow()方法來得到一個數(shù)字的冪。有一種更短的語法來實現(xiàn),即雙星號 (**)。

 

  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 

 

來自 Caleb 的評論的改進: 雙非位運算符只對 32 位整數(shù)有效,例如 (2**31)-1 = 2147483647。所以對于任何大于 2147483647 的數(shù)字,雙非位運算符 (~~) 都會給出錯誤的結果,這種情況下推薦使用 Math.floor() 方法。

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

我們可以使用 for 循環(huán)來遍歷數(shù)組中的每一個值,然后找出最大或最小值。我們還可以使用 Array.reduce() 方法來找出數(shù)組中的最大和最小數(shù)字。

但是使用擴展符號,我們一行就可以實現(xiàn)。

 

  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來遍歷數(shù)組。為了獲取每個值的索引,我們可以使用for...in循環(huán)。

 

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

 

參考:JavaScript 中遍歷對象和數(shù)組的不同方法

https://jscurious.com/different-ways-to-iterate-through-objects-and-arrays-in-javascript/

18. 合并數(shù)組

 

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

 

19. 深拷貝多級對象

為了深拷貝一個多級對象,我們要遍歷每一個屬性并檢查當前屬性是否包含一個對象。如果當前屬性包含一個對象,然后要將當前屬性值作為參數(shù)遞歸調用相同的方法(例如,嵌套的對象)。

我們可以使用JSON.stringify()和JSON.parse(),如果我們的對象不包含函數(shù)、undefined、NaN 或日期值的話。

如果有一個單級對象,例如沒有嵌套的對象,那么我們也可以使用擴展符來實現(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)); 
  16. //Shorthand for single level object 
  17. let obj = {x: 20, y: 'hello'}; 
  18. const cloneObj = {...obj}; 

 

來自評論的改進:如果你的對象包含 function, undefined or NaN 值的話,JSON.parse(JSON.stringify(obj)) 就不會有效。因為當你 JSON.stringify 對象的時候,包含 function, undefined or NaN 值的屬性會從對象中移除。因此,當你的對象只包含字符串和數(shù)字值時,可以使用JSON.parse(JSON.stringify(obj))。

參考:JSON.parse() 和 JSON.stringify()

https://jscurious.com/difference-between-json-parse-and-json-stringify/

20. 獲取字符串中的字符

 

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

 

責任編輯:華軒 來源: 今日頭條
相關推薦

2025-01-07 10:48:08

2023-09-26 00:00:20

JS簡寫技巧

2018-12-07 10:30:50

盤點CSS前端

2021-06-17 07:45:35

Javascript 技巧效率

2018-01-04 16:32:30

前端JavaScript

2022-08-16 10:53:56

JavaScript前端技巧

2020-11-11 08:22:40

前端開發(fā)JavaScript

2009-06-10 21:58:51

Javascript常

2017-10-24 11:59:41

JavaScript

2023-10-23 15:02:53

JavaScript

2025-04-11 08:26:41

2010-10-08 09:42:23

JavaScript方

2022-11-07 16:25:07

JavaScript技巧

2025-02-26 12:00:00

JavaScript代碼開發(fā)

2023-10-18 10:21:23

JavaScript前端

2023-05-24 16:39:30

CSS技巧開發(fā)

2020-12-09 11:52:28

Python字符串代碼

2020-05-22 11:20:56

Linux命令文件

2022-12-22 14:44:06

JavaScript技巧

2022-12-25 16:03:31

JavaScript技巧
點贊
收藏

51CTO技術棧公眾號