任何編程語言的簡寫技巧都能夠幫助你編寫更簡練的代碼墓怀,讓你用更少的代碼實現(xiàn)你的目標蛤铜。讓我們一個個來看看 JavaScript 的簡寫技巧吧。
1. 聲明變量
//Longhand
let x;let y = 20;
//Shorthand
let x, y = 20;
2. 給多個變量賦值
我們可以使用數(shù)組解構(gòu)來在一行中給多個變量賦值姚建。
//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(||) 短路運算來給一個變量賦默認值,如果預(yù)期值不正確的情況下阳仔。
//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 時調(diào)用一個函數(shù)忧陪,那么你可以使用與 (&&)
短路形式書寫。
//Longhand
if (isLoggedin) { goToHomepage();}
//Shorthand
isLoggedin && goToHomepage();
當你在 React 中想要有條件地渲染某個組件時近范,這個與 (&&)
短路寫法比較有用嘶摊。例如:
<div> { this.state.isLoading && <Loading /> } </div>
6. 交換兩個變量
為了交換兩個變量,我們通常使用第三個變量评矩。我們可以使用數(shù)組解構(gòu)賦值來交換兩個變量叶堆。
let x = 'Hello', y = 55;//Longhandconst temp = x;x = y;y = temp;//Shorthand[x, y] = [y, x];
7. 箭頭函數(shù)
//Longhand
function add(num1, num2) { return num1 + num2;}
//Shorthandconst 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. 多行字符串
對于多行字符串,我們一般使用 + 運算符以及一個新行轉(zhuǎn)義字符(\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. 對象屬性復(fù)制
如果變量名和對象的屬性名相同,那么我們只需要在對象語句中聲明變量名,而不是同時聲明鍵和值锈玉。JavaScript 會自動將鍵作為變量的名爪飘,將值作為變量的值。
let firstname = 'Amitav';
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};
//Shorthand
let obj = {firstname, lastname};
12. 字符串轉(zhuǎn)成數(shù)字
有一些內(nèi)置的方法拉背,例如parseInt
和parseFloat
可以用來將字符串轉(zhuǎn)為數(shù)字师崎。我們還可以簡單地在字符串前提供一個一元運算符 (+) 來實現(xiàn)這一點。
//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
//Shorthandlet
total = +'453';
let average = +'42.6';
13. 重復(fù)一個字符串多次為了重復(fù)一個字符串 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() 方法試試吧。如果你想要每次在新的一行重復(fù)字符串诱渤,可以在字符串后面加一個 \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ù)字,雙非位運算符 (~~) 都會給出錯誤的結(jié)果占卧,這種情況下推薦使用 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ù)遞歸調(diào)用相同的方法(例如渊跋,嵌套的對象)腊嗡。
我們可以使用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 objectlet 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
原文
原作者 | Amitav Mishra