網站首頁 前端文檔 正文
前言:
最近看了一些簡化JS代碼的文章,其中有一篇覺得還不錯,但是是英文的,也看了一些中文翻譯,一個是一字一句翻譯太生硬,沒有變成自己的東西,另外就是后面作者有新增沒有及時更新,于是我按照自己的語言翻譯整理成此文,本文特點以言簡意賅為主
當同時聲明多個變量時,可簡寫成一行
//Longhand let x; let y = 20; //Shorthand let x, y = 20;
利用解構,可為多個變量同時賦值
//Longhand let a, b, c; a = 5; b = 8; c = 12; //Shorthand let [a, b, c] = [5, 8, 12];
巧用三元運算符簡化if else
//Longhand let marks = 26; let result; if (marks >= 30) { result = 'Pass'; } else { result = 'Fail'; } //Shorthand let result = marks >= 30 ? 'Pass' : 'Fail';
使用||運算符給變量指定默認值
本質是利用了||運算符的特點,當前面的表達式的結果轉成布爾值為false
時,則值為后面表達式的結果
//Longhand let imagePath; let path = getImagePath(); if (path !== null && path !== undefined && path !== '') { imagePath = path; } else { imagePath = 'default.jpg'; } //Shorthand let imagePath = getImagePath() || 'default.jpg';
使用&&運算符簡化if語句
例如某個函數(shù)在某個條件為真時才調用,可簡寫
//Longhand if (isLoggedin) { goToHomepage(); } //Shorthand isLoggedin && goToHomepage();
使用解構交換兩個變量的值
let x = 'Hello', y = 55; //Longhand const temp = x; x = y; y = temp; //Shorthand [x, y] = [y, x];
適用箭頭函數(shù)簡化函數(shù)
//Longhand function add(num1, num2) { return num1 + num2; } //Shorthand const add = (num1, num2) => num1 + num2;
需要注意箭頭函數(shù)和普通函數(shù)的區(qū)別
使用字符串模板簡化代碼
使用模板字符串代替原始的字符串拼接
//Longhand console.log('You got a missed call from ' + number + ' at ' + time); //Shorthand console.log(`You got a missed call from ${number} at ${time}`);
多行字符串也可使用字符串模板簡化
//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.` );
對于多值匹配,可將所有值放在數(shù)組中,通過數(shù)組方法來簡寫
//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 }
巧用ES6對象的簡潔語法
例如:當屬性名和變量名相同時,可直接縮寫為一個
let firstname = 'Amitav'; let lastname = 'Mishra'; //Longhand let obj = {firstname: firstname, lastname: lastname}; //Shorthand let obj = {firstname, lastname};
使用一元運算符簡化字符串轉數(shù)字
//Longhand let total = parseInt('453'); let average = parseFloat('42.6'); //Shorthand let total = +'453'; let average = +'42.6';
使用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); // 想跟你說100聲抱歉! 'sorry\n'.repeat(100);
使用雙星號代替Math.pow()
//Longhand const power = Math.pow(4, 3); // 64 // Shorthand const power = 4**3; // 64
使用雙波浪線運算符(~~)代替Math.floor()
//Longhand const floor = Math.floor(6.8); // 6 // Shorthand const floor = ~~6.8; // 6
需要注意,~~僅適用于小于2147483647的數(shù)字
巧用擴展操作符(...)簡化代碼
簡化數(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]
單層對象的拷貝
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};
尋找數(shù)組中的最大和最小值
// Shorthand const arr = [2, 8, 15, 4]; Math.max(...arr); // 15 Math.min(...arr); // 2
使用for in和for of來簡化普通for循環(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]); }
簡化獲取字符串中的某個字符
let str = 'jscurious.com'; //Longhand str.charAt(2); // c //Shorthand str[2]; // c
移除對象屬性
let obj = {x: 45, y: 72, z: 68, p: 98}; // Longhand delete obj.x; delete obj.p; console.log(obj); // {y: 72, z: 68} // Shorthand let {x, p, ...newObj} = obj; console.log(newObj); // {y: 72, z: 68}
使用arr.filter(Boolean)過濾掉數(shù)組成員的值falsey
let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false]; //Longhand let filterArray = arr.filter(function(value) { if(value) return value; }); // filterArray = [12, "xyz", -25, 0.5] // Shorthand let filterArray = arr.filter(Boolean); // filterArray = [12, "xyz", -25, 0.5]
原文鏈接:https://juejin.cn/post/7041068640094912548
相關推薦
- 2022-06-16 C語言從猜數(shù)字游戲中理解數(shù)據結構_C 語言
- 2022-07-03 無緩沖channel的內存泄漏問題
- 2022-08-21 android實現(xiàn)可以滑動的平滑曲線圖_Android
- 2022-05-10 gin實現(xiàn)限流中間件
- 2022-10-18 C++數(shù)據結構之二叉搜索樹的實現(xiàn)詳解_C 語言
- 2022-12-12 Android?Google?AutoService框架使用詳解_Android
- 2022-07-13 Linux OS 運行python腳本中smtplib has no attribute SMTP_
- 2022-08-02 Go語言kylin任務自動化實例詳解_Golang
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支