JavaScript速記技巧:向著更清晰的代碼邁進(jìn)
本文轉(zhuǎn)載自公眾號“讀芯術(shù)”(ID:AI_Discovery)。
無論是哪個(gè)編程語言的速記技巧,都有助于你編寫更好、更清晰的代碼。借助速記技巧,不僅可以提升代碼可讀性,還可以編寫更少代碼完成任務(wù)。下面是一些JavaScript的速記技巧。
1. 聲明變量
- //Longhand
- let x;
- let y = 20;
- //Shorthand
- let x, y = 20;
2. 給多個(gè)變量賦值
可以在一行代碼中給多個(gè)變量同時(shí)賦值。
- //Longhand
- let marks = 26;
- let result;
- if(marks >= 30){
- result = 'Pass';
- }else{
- result = 'Fail';
- }
- //Shorthand
- let result = marks >= 30 ? 'Pass' : 'Fail';
3. 三元運(yùn)算符
使用三元運(yùn)算符(條件),五行代碼可以簡化為一行。
- //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. 分配默認(rèn)值
我們可以使用OR(||)短路評估為變量指定一個(gè)默認(rèn)值,以防期望值為空。
- //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(&&)短路評估
如需只在變量為真的情況下調(diào)用一個(gè)函數(shù),則可使用AND(&&)短路評估在一行內(nèi)完成。
- //Longhand
- if (isLoggedin) {
- goToHomepage();
- }
- //Shorthand
- isLoggedin && goToHomepage();
速記寫法這一行,只有在isLoggedin返回結(jié)果為真時(shí),goToHomepage()才會執(zhí)行。
6. 交換兩個(gè)變量
通常交換兩個(gè)變量需要借助第三個(gè)變量。然而通過數(shù)組析構(gòu)賦值,可以輕松交換兩個(gè)變量。
- //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. 箭頭函數(shù)
- //Longhand
- function add(num1, num2) {
- return num1 + num2;
- }
- //Shorthand
- const add = (num1, num2) => num1 + num2;
8. 模板文字
我們通常使用“+”運(yùn)算符連接字符串值和變量。有了ES6模板,我們可以通過一種更簡單的方式實(shí)現(xiàn)。
- //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. 多行字符串
對于多行字符串,我們通常使用“+”運(yùn)算符和換行轉(zhuǎn)義符(\n)進(jìn)行連接。然而可以使用“`”簡化代碼。
- let firstname = 'Amitav';
- let lastname = 'Mishra'; //Longhand
- let obj = {firstname: firstname, lastname: lastname};
- //Shorthand
- let obj = {firstname, lastname};
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. 對象屬性分配
如果變量名和對象鍵名相同,可以只在對象文字中設(shè)置變量名,不用同時(shí)設(shè)置鍵和值。JavaScript會自動(dòng)將鍵名設(shè)置為變量名,并將該值賦為變量值。
- 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ù)字。更簡單的方法是,在字符串值前加上一元運(yùn)算符(+)。
- //Longhand
- let total = parseInt('453');
- let average = parseFloat('42.6');
- //Shorthand
- let total = +'453';
- let average = +'42.6';
13. 多次重復(fù)同一字符串
若要將字符串重復(fù)指定的次數(shù),可以使用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次“對不起”進(jìn)行道歉?試試repeat()方法。如果你想在每次重復(fù)時(shí)另起一行,只需加上\n。
14. 指數(shù)冪
我們可以用Math.pow()方法求冪。然而用雙星號(**)有一個(gè)更短的語法。
- //Longhand
- const power = Math.pow(4, 3); // 64
- // Shorthand
- const power = 4**3; // 64
15. 按位雙非運(yùn)算符
按位雙非運(yùn)算符可以替代Math.floor()方法。
- //Longhand
- const floor = Math.floor(6.8); // 6
- // Shorthand
- const floor = ~~6.8; // 6
按位雙非運(yùn)算符方法僅適用于32位整數(shù),即(2**31)-1 = 2147483647。所以對于任何高于2147483647的數(shù)字,按位運(yùn)算符(~~)都會給出錯(cuò)誤的結(jié)果,所以在這種情況下建議使用Math.floor()。
16. 找出數(shù)組的最大值和最小值
可以使用for循環(huán)遍歷數(shù)組的每個(gè)值,從而找到最大值或最小值。也可以使用Array.reduce()方法來查找數(shù)組中的最大值和最小值。
但是使用擴(kuò)展運(yù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 循環(huán)進(jìn)行遍歷。如需訪問每個(gè)值的索引,可以使用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]);
- }
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. 多級對象的深度克隆
要深度克隆多級對象,可以遍歷每個(gè)屬性,并檢查當(dāng)前屬性是否包含對象。如果是,則通過傳遞當(dāng)前屬性值(即嵌套對象)對同一函數(shù)進(jìn)行遞歸調(diào)用。也可以使用JSON.stringify()和JSON.parse()在一行中實(shí)現(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));
如果對象屬性以函數(shù)作為值,則速記技巧(JSON.parse(JSON.stringify(obj)))無效。因?yàn)镴SON.stringif作用于對象時(shí),以函數(shù)作為值的屬性會從對象中移除。所以這種情況下,還是要用普通寫法。
20. 從字符串中獲取字符
- let str = 'jscurious.com'; //Longhand
- str.charAt(2); // c
- //Shorthand
- str[2]; // c
希望本文能讓你有所收獲。