25 条示例代码让你的代码更简洁 JavaScript 无处不在,从 PC 端到移动设备端,甚至是后端,都在使用 JavaScript。
在本文中,我将尝试一些可用来使代码看起来更简洁的实践方案。
1、使用默认参数代替短路或条件 默认参数通常比短路更简洁。
1 2 3 4 5 6 7 function SomeMethod (paramThatCanBeUndefined ) { const localValue = paramThatCanBeUndefined || "Default Value" ; console .log (localValue); } SomeMethod (); SomeMethod ("SomeValue" );
尝试以下方法:
1 2 3 4 5 6 function SomeMethod ( console .log(paramThatCanBeUndefined) } SomeMethod() SomeMethod("SomeValue" )
声明:Falsy 值,如’’,””,false,null,0,和 NaN 将不会被默认值替代:
1 2 3 4 5 6 function SomeMethod (paramThatCanBeUndefined = "Default Value" ) { console .log (paramThatCanBeUndefined); } SomeMethod (null ); SomeMethod ("SomeValue" );
2、处理多个条件 1 2 3 4 5 6 7 8 const conditions = ["Condition 2" ,"Condition String2" ];someFunction (str ){ if (str.includes ("someValue1" ) || str.includes ("someValue2" )){ return true }else { return false } }
一种更简洁的方法是:
1 2 3 4 someFunction (str ){ const conditions = ["someValue1" ,"someValue2" ]; return conditions.some (condition => str.includes (condition)); }
3、用动态键值对替换开关(即对象文字) 开关版本(或将开关替换为 if / else):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 const UserRole = { ADMIN : "Admin" , GENERAL_USER : "GeneralUser" , SUPER_ADMIN : "SuperAdmin" , }; function getRoute (userRole = "default role" ) { switch (userRole) { case UserRole .ADMIN : return "/admin" ; case UserRole .GENERAL_USER : return "/GENERAL_USER" ; case UserRole .SUPER_ADMIN : return "/superadmin" ; default : return "/" ; } } console .log (getRoute (UserRole .ADMIN )); console .log (getRoute ("Anything" )); console .log (getRoute ()); console .log (getRoute (null ));
动态键值对版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 const UserRole = { ADMIN : "Admin" , GENERAL_USER : "GeneralUser" , SUPER_ADMIN : "SuperAdmin" , }; function getRoute (userRole = "default role" ) { const appRoute = { [UserRole .ADMIN ]: "/admin" , [UserRole .GENERAL_USER ]: "/user" , [UserRole .SUPER_ADMIN ]: "/superadmin" , }; return appRoute[userRole] || "Default path" ; } console .log (getRoute (UserRole .ADMIN )); console .log (getRoute ("Anything" )); console .log (getRoute ()); console .log (getRoute (null ));
4、避免过多的函数参数 1 2 3 4 5 6 7 8 9 10 11 function myFunction (employeeName, jobTitle, yrExp, majorExp ) { return `${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp} ` ; } console .log (myFunction ("John" , "Project Manager" , 12 , "Project Management" ));
这是一种更清洁的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 function myFunction ({ employeeName, jobTitle, yrExp, majorExp } ) { return `${employeeName} is working as ${jobTitle} with ${yrExp} years of experience in ${majorExp} ` ; } const mockTechPeople = { employeeName : "John" , jobTitle : "Project Manager" , yrExp : 12 , majorExp : "Project Management" , }; console .log (myFunction (mockTechPeople));
5、使用 Object.assign 设置默认对象 这看起来很繁琐:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 const someObject = { title : null , subTitle : "Subtitle" , buttonColor : null , disabled : true , }; function createOption (someObject ) { someObject.title = someObject.title || "Default Title" ; someObject.subTitle = someObject.subTitle || "Default Subtitle" ; someObject.buttonColor = someObject.buttonColor || "blue" ; someObject.disabled = someObject.disabled !== undefined ? someObject.disabled : true ; return someObject; } console .log (createOption (someObject));
这种方法看起来更好:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 const someObject = { title : null , subTitle : "Subtitle" , buttonColor : null , disabled : true , }; function creteOption (someObject ) { const newObject = Object .assign ( { title : "Default Title" , subTitle : "Default Subtitle" , buttonColor : "blue" , disabled : true , }, someObject ); return newObject; } console .log (creteOption (someObject));
6.通过条件判断给变量赋值布尔值的正确姿势 1 2 3 4 5 6 7 8 9 if (a === "a" ) { b = true ; } else { b = false ; } b = a === "a" ;
7.在 if 中判断数组长度不为零的正确姿势 1 2 3 4 5 6 7 8 9 if (arr.length !== 0 ) { } if (arr.length ) { }
8.同理,在 if 中判断数组长度为零的正确姿势 1 2 3 4 5 6 7 8 9 if (arr.length === 0 ) { } if (!arr.length ) { }
9.简单的 if 判断使用三元表达式 1 2 3 4 5 6 7 8 9 if (a === "a" ) { b = a; } else { b = c; } b = a === "a" ? a : c;
10.使用 includes 简化 if 判断 1 2 3 4 5 6 7 8 9 10 if (a === 1 || a === 2 || a === 3 || a === 4 ) { } let arr = [1 , 2 , 3 , 4 ];if (arr.includes (a)) { }
巧用数组方法,尽量避免用 for 循环
11.使用 some 方法判断是否有满足条件的元素 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 let arr = [1 , 3 , 5 , 7 ];function isHasNum (n ) { for (let i = 0 ; i < arr.length ; i++) { if (arr[i] === n) { return true ; } } return false ; } let arr = [1 , 3 , 5 , 7 ];let isHasNum = (n ) => arr.some ((num ) => num === n);let arr = [1 , 3 , 5 , 7 ];let isHasNum = (n, arr ) => arr.some ((num ) => num === n);
12.使用 forEach 方法遍历数组,不形成新数组 1 2 3 4 5 6 7 8 9 10 11 for (let i = 0 ; i < arr.length ; i++) { arr[i].key = balabala; } arr.forEach ((item ) => { item.key = balabala; });
13.使用 filter 方法过滤原数组,形成新数组 1 2 3 4 5 6 7 8 9 10 11 12 let arr = [1 , 3 , 5 , 7 ], newArr = []; for (let i = 0 ; i < arr.length ; i++) { if (arr[i] > 4 ) { newArr.push (arr[i]); } } let arr = [1 , 3 , 5 , 7 ];let newArr = arr.filter ((n ) => n > 4 );
14.使用 map 对数组中所有元素批量处理,形成新数组 1 2 3 4 5 6 7 8 9 10 let arr = [1 , 3 , 5 , 7 ], newArr = []; for (let i = 0 ; i < arr.length ; i++) { newArr.push (arr[i] + 1 ); } let arr = [1 , 3 , 5 , 7 ];let newArr = arr.map ((n ) => n + 1 );
巧用对象方法,避免使用 for…in
15.使用 Object.values 快速获取对象键值 1 2 3 4 5 6 7 8 9 10 11 12 let obj = { a : 1 , b : 2 , }; let values = [];for (key in obj) { values.push (obj[key]); } let values = Object .values (obj);
16.使用 Object.keys 快速获取对象键名 1 2 3 4 5 6 7 8 9 10 11 12 let obj = { a : 1 , b : 2 , }; let keys = [];for (value in obj) { keys.push (value); } let keys = Object .keys (obj);
巧用解构简化代码
17.解构数组进行变量值的替换 1 2 3 4 5 6 7 8 9 10 let a = 1 , b = 2 ; let temp = a;a = b; b = temp; let a = 1 , b = ((2 )[(b, a)] = [a, b]);
18.解构对象 1 2 3 4 5 6 7 8 9 10 11 12 13 setForm (person) { this .name = person.name this .age = person.age } setForm ({name, age}) { this .name = name this .age = age }
19.解构时重命名简化命名 有的后端返回的键名特别长,你可以这样干
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 setForm (data) { this .one = data.aaa_bbb_ccc_ddd this .two = data.eee_fff_ggg } setForm ({aaa_bbb_ccc_ddd, eee_fff_ggg}) { this .one = aaa_bbb_ccc_ddd this .two = eee_fff_ggg } setForm ({aaa_bbb_ccc_ddd : one, eee_fff_ggg : two}) { this .one = one this .two = two }
20.解构时设置默认值 1 2 3 4 5 6 7 8 9 10 11 12 13 14 setForm ({name, age}) { if (!age) age = 16 this .name = name this .age = age } setForm ({name, age = 16 }) { this .name = name this .age = age }
21.||短路符设置默认值 1 2 3 4 5 6 let person = { name : "张三" , age : 38 , }; let name = person.name || "佚名" ;
22.&&短路符判断依赖的键是否存在防止报错’xxx of undfined’ 1 2 3 4 5 6 7 8 9 let person = { name : "张三" , age : 38 , children : { name : "张小三" , }, }; let childrenName = person.children && person.childre .name ;
23.字符串拼接使用${}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 let person = { name : 'LiMing' , age : 18 } function sayHi (obj) { console .log ('大家好,我叫' + person.name = ',我今年' + person.age + '了' ) } function sayHi (person) { console .log (`大家好,我叫${person.name} ,我今年${person.age} 了` ) } function sayHi ({name, age}) { console .log (`大家好,我叫${name} ,我今年${age} 了` ) }
24.函数使用箭头函数 1 2 3 4 5 6 7 8 9 10 11 12 let arr [18 , 19 , 20 , 21 , 22 ]function findStudentByAge (arr, age) { return arr.filter (function (num ) { return num === age }) } let findStudentByAge = (arr, age )=> arr.filter (num => num === age)
25.函数参数校验 1 2 3 4 5 6 7 8 9 10 11 12 let findStudentByAge = (arr, age ) => { if (!age) throw new Error ("参数不能为空" ); return arr.filter ((num ) => num === age); }; let checkoutType = ( ) => { throw new Error ("参数不能为空" ); }; let findStudentByAge = (arr, age = checkoutType() ) => arr.filter ((num ) => num === age);
欢迎大佬们指正交流,感谢支持