javascriptThe column introduces tips to improve the quality of article code
Recommended (free) :javascript(Video)
Introduction
Mainly introduces the following points:
Refining function
Merge duplicate conditional fragments
Refining conditional branch statements into functions
Use loops appropriately
Let the function exit early instead of nested conditional branches
Pass object parameters instead of too long parameter lists
Use less ternary operators
Use chain calls rationally
Decompose large classes
This article will be continuously updated, please feel free to add any deficiencies in the comment area.
1. Refining functions
Benefits:
Avoid overly large functions.
Independent functions help code reuse.
Independent functions are easier to overwrite.
If the independent function has a good name, it itself plays the role of a comment.
Semantic implementation of multiple separate sections of logic in different functions can make the code logic clear and clearly see what each step is doing.
Code example:
Realize obtaining data, then operate dom to display data, and finally add events
Before function refining
// 逻辑都写在一起,需要将所有逻辑看完才知道这段代码是干嘛的,局部逻辑无法复用 function main() { $.ajax.get('/getData').then((res) => { const ul = document.getElementById('ul'); ul.innerHTML = res.list.map(text => `
After function refining
function getData() { return $.ajax.get('/getData').then((res) => res.data.list); } function showList(list) { const ul = document.getElementById('ul'); ul.innerHTML = list.map(text => `
2. Merge duplicate conditional fragments
If there are some conditional branch statements in a function body, and there are some repeated conditional statements scattered inside these conditional branch statements code, then it is necessary to merge and remove duplicates.
// 合并前 function main( currPage ){ if ( currPage <= 0 ){ currPage = 0; jump( currPage ); // 跳转 }else if ( currPage >= totalPage ){ currPage = totalPage; jump( currPage ); // 跳转 }else{ jump( currPage ); // 跳转 } }; // 合并后 function main( currPage ){ if ( currPage <= 0 ){ currPage = 0; }else if ( currPage >= totalPage ){ currPage = totalPage; } jump( currPage ); // 把jump 函数独立出来 };
3. Refining conditional branch statements into functions
Complex conditional branch statements are an important reason why the program is difficult to read and understand, and can easily lead to a huge function. Sometimes conditional branch statements can be refined into semantic functions to make the code more intuitive and logically clear.
// 根据不同季节决定打折力度 function getPrice( price ){ var date = new Date(); if ( date.getMonth() >= 6 && date.getMonth() <= 9 ){ // 夏天 return price * 0.8; } return price; }; // 是否是夏天 function isSummer(){ var date = new Date(); return date.getMonth() >= 6 && date.getMonth() <= 9; }; // 提炼条件后 function getPrice( price ){ if ( isSummer() ){ return price * 0.8; } return price; };
4. Reasonable use of loops
If multiple pieces of code are actually responsible for some repetitive work, they can be replaced by loops to reduce the amount of code.
// 判断是什么浏览器 function getBrowser(){ const str = navigator.userAgent; if (str.includes('QQBrowser')) { return 'qq'; } else if (str.includes('Chrome')) { return 'chrome'; } else if (str.includes('Safari')) { return 'safri'; } else if (str.includes('Firefox')) { return 'firefox'; } else if(explorer.indexOf('Opera') >= 0){ return 'opera'; } else if (str.includes('msie')) { return 'ie'; } else { return 'other'; } }; // 循环判断,将对应关系抽象为配置,更加清晰明确 function getBrowser(){ const str = navigator.userAgent; const list = [ {key: 'QQBrowser', browser: 'qq'}, {key: 'Chrome', browser: 'chrome'}, {key: 'Safari', browser: 'safari'}, {key: 'Firefox', browser: 'firefox'}, {key: 'Opera', browser: 'opera'}, {key: 'msie', browser: 'ie'}, ]; for (let i = 0; i < list.length; i++) { const item = list[i]; if (str.includes(item.key)) {return item.browser}; } return 'other'; }
5. Let the function exit early instead of nested conditional branches
Let the function return early with multiple exits and replace nested conditional branches.
function del( obj ){ var ret; if ( !obj.isReadOnly ){ // 不为只读的才能被删除 if ( obj.isFolder ){ // 如果是文件夹 ret = deleteFolder( obj ); }else if ( obj.isFile ){ // 如果是文件 ret = deleteFile( obj ); } } return ret; }; function del( obj ){ if ( obj.isReadOnly ){ // 反转if 表达式 return; } if ( obj.isFolder ){ return deleteFolder( obj ); } if ( obj.isFile ){ return deleteFile( obj ); } };
6. Pass object parameters instead of too long parameter lists
If the function parameters are too long, the risk of errors increases. It is important to ensure that the order of passing is correct. The trouble is that the readability of the code will also become worse. Try to ensure that the parameters of the function are not too long. If multiple parameters must be passed, it is recommended to use objects instead.
Generally speaking, it is best not to have more than 3 function parameters
function setUserInfo( id, name, address, sex, mobile, qq ){ console.log( 'id= ' + id ); console.log( 'name= ' +name ); console.log( 'address= ' + address ); console.log( 'sex= ' + sex ); console.log( 'mobile= ' + mobile ); console.log( 'qq= ' + qq ); }; setUserInfo( 1314, 'sven', 'shenzhen', 'male', '137********', 377876679 ); function setUserInfo( obj ){ console.log( 'id= ' + obj.id ); console.log( 'name= ' + obj.name ); console.log( 'address= ' + obj.address ); console.log( 'sex= ' + obj.sex ); console.log( 'mobile= ' + obj.mobile ); console.log( 'qq= ' + obj.qq ); }; setUserInfo({ id: 1314, name: 'sven', address: 'shenzhen', sex: 'male', mobile: '137********', qq: 377876679 });
7. Use less ternary operators
Ternary operator performance High, less code.
But the ternary operator should not be abused. We should use it in simple logic branches and avoid using it in complex logic branches.
// 简单逻辑可以使用三目运算符 var global = typeof window !== "undefined" ? window : this; // 复杂逻辑不适合使用 var ok = isString ? (isTooLang ? 2 : (isTooShort ? 1 : 0)) : -1;
8. Reasonable use of chain calls
Advantages:
Chain calls are simple to use and require less code.
Disadvantages:
The disadvantage of chain calls is that it is inconvenient to debug. If we know that there is an error in a chain, we must first disassemble the chain before adding some Debug the log or add breakpoints to locate where the error occurs.
If the structure of the chain is relatively stable and not easy to be modified later, the chain type can be used.
var User = { id: null, name: null, setId: function( id ){ this.id = id; return this; }, setName: function( name ){ this.name = name; return this; } }; User .setId( 1314 ) .setName( 'sven' ); var user = new User(); user.setId( 1314 ); user.setName( 'sven' );
9. Decomposing large classes
The decomposition of large classes is very similar to the refining of functions. If a class is too large, the logic will be unclear and difficult to understand and maintain.
Reasonable decomposition of major categories can make the logic of the class clear, and sub-modules can be easily reused.
10. Use bitwise operators
The performance of programming languages for calculating multiplication and division is not high, but in some cases, using bitwise operators can improve the performance of operations such as multiplication and division.
// 按位右移 var n = parseInt(3 / 2); // 原始 var n = 3 >> 1; // 按位右移
The above is the detailed content of Master JavaScript tips to help you improve code quality. For more information, please follow other related articles on the PHP Chinese website!