20個常用的JavaScript簡寫技巧
任何編程語言的簡寫技巧都能夠幫助你編寫更簡練的代碼,讓你用更少的代碼實現(xiàn)你的目標。讓我們一個個來看看 JavaScript 的簡寫技巧吧。
1. 聲明變量
- //Longhand
- let x;
- let y = 20;
- //Shorthand
- let x, y = 20;
2. 給多個變量賦值
我們可以使用數(shù)組解構來在一行中給多個變量賦值。
- //Longhand
- let a, b, c;
- a = 5;
- b = 8;
- c = 12;
- //Shorthand
- let [a, b, c] = [5, 8, 12];
3. 三元運算符
我們可以使用三元(條件)運算符在這里節(jié)省 5 行代碼。
- //Longhand
- let marks = 26;
- let result;
- if(marks >= 30){
- result = 'Pass';
- }else{
- result = 'Fail';
- }
- //Shorthand
- let result = marks >= 30 ? 'Pass' : 'Fail';
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. 與 (&&) 短路運算
如果你只有當某個變量為 true 時調用一個函數(shù),那么你可以使用與 (&&)短路形式書寫。
- //Longhand
- if (isLoggedin) {
- goToHomepage();
- }
- //Shorthand
- isLoggedin && goToHomepage();
當你在 React 中想要有條件地渲染某個組件時,這個與 (&&)短路寫法比較有用。例如:
- <div> { this.state.isLoading && <Loading /> } </div>
6. 交換兩個變量
為了交換兩個變量,我們通常使用第三個變量。我們可以使用數(shù)組解構賦值來交換兩個變量。
- let x = 'Hello', y = 55;
- //Longhand
- const temp = x;
- x = y;
- y = temp;
- //Shorthand
- [x, y] = [y, x];
7. 箭頭函數(shù)
- //Longhand
- function add(num1, num2) {
- return num1 + num2;
- }
- //Shorthand
- const add = (num1, num2) => num1 + num2;
參考:JavaScript Arrow function
https://jscurious.com/javascript-arrow-function/
8. 模板字符串
我們一般使用 + 運算符來連接字符串變量。使用 ES6 的模板字符串,我們可以用一種更簡單的方法實現(xiàn)這一點。
- //Longhand
- console.log('You got a missed call from ' + number + ' at ' + time);
- //Shorthand
- console.log(`You got a missed call from ${number} at ${time}`);
9. 多行字符串
對于多行字符串,我們一般使用 + 運算符以及一個新行轉義字符(\n)。我們可以使用 (`) 以一種更簡單的方式實現(xiàn)。
- //Longhand
- console.log('JavaScript, often abbreviated as JS, is a\n' + 'programming language that conforms 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 language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.`);
10. 多條件檢查
對于多個值匹配,我們可以將所有的值放到數(shù)組中,然后使用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. 字符串轉成數(shù)字
有一些內置的方法,例如parseInt和parseFloat可以用來將字符串轉為數(shù)字。我們還可以簡單地在字符串前提供一個一元運算符 (+) 來實現(xiàn)這一點。
- //Longhand
- let total = parseInt('453');
- let average = parseFloat('42.6');
- //Shorthand
- let total = +'453';
- let average = +'42.6';
13. 重復一個字符串多次為了重復一個字符串 N 次,你可以使用for循環(huán)。但是使用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);提示: 想要給某人發(fā) 100 遍“sorry”來道歉嗎?用 repeat() 方法試試吧。如果你想要每次在新的一行重復字符串,可以在字符串后面加一個 \n 。
- 'sorry\n'.repeat(100);
14. 指數(shù)冪
我們可以使用Math.pow()方法來得到一個數(shù)字的冪。有一種更短的語法來實現(xiàn),即雙星號 (**)。
- //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
來自 Caleb 的評論的改進: 雙非位運算符只對 32 位整數(shù)有效,例如 (2**31)-1 = 2147483647。所以對于任何大于 2147483647 的數(shù)字,雙非位運算符 (~~) 都會給出錯誤的結果,這種情況下推薦使用 Math.floor() 方法。
16. 找出數(shù)組中的最大和最小數(shù)字
我們可以使用 for 循環(huán)來遍歷數(shù)組中的每一個值,然后找出最大或最小值。我們還可以使用 Array.reduce() 方法來找出數(shù)組中的最大和最小數(shù)字。
但是使用擴展符號,我們一行就可以實現(xiàn)。
- // Shorthand
- const arr = [2, 8, 15, 4];
- Math.max(...arr); // 15
- Math.min(...arr); // 2
17. For 循環(huán)
為了遍歷一個數(shù)組,我們一般使用傳統(tǒng)的for循環(huán)。我們可以使用for...of來遍歷數(shù)組。為了獲取每個值的索引,我們可以使用for...in循環(huán)。
- 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循環(huán)來遍歷對象屬性。
- let obj = {x: 20, y: 50};
- for (const key in obj) {
- console.log(obj[key]);
- }
參考:JavaScript 中遍歷對象和數(shù)組的不同方法
https://jscurious.com/different-ways-to-iterate-through-objects-and-arrays-in-javascript/
18. 合并數(shù)組
- 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. 深拷貝多級對象
為了深拷貝一個多級對象,我們要遍歷每一個屬性并檢查當前屬性是否包含一個對象。如果當前屬性包含一個對象,然后要將當前屬性值作為參數(shù)遞歸調用相同的方法(例如,嵌套的對象)。
我們可以使用JSON.stringify()和JSON.parse(),如果我們的對象不包含函數(shù)、undefined、NaN 或日期值的話。
如果有一個單級對象,例如沒有嵌套的對象,那么我們也可以使用擴展符來實現(xiàn)深拷貝。
- 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));
- //Shorthand for single level object
- let obj = {x: 20, y: 'hello'};
- 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. 獲取字符串中的字符
- let str = 'jscurious.com';
- //Longhand
- str.charAt(2); // c
- //Shorthand
- str[2]; // c