js高级写法
|
| 一般寫法 | 優(yōu)化 |
| 取整(不四舍五入) | parseInt(a,10); //Before Math.floor(a); //Before a>>0; //Before | ~~a; //After a|0; //After ? |
| 取整(四舍五入) | Math.round(a); //Before | a+.5|0; //After |
| 未定義 | undefined; //Before | void 0; //After, 快 0[0]; //After, 略慢 |
| 布爾值短寫法 | true; //Before | !0; //After |
| 串連字符串 | ''+a+b+c; //before | ''.concat(a, b, c); |
| 字符串截取 | str.charAt(0); //before | str[0] //after |
| 獲取數(shù)組是否存在元素 | for循環(huán) | [1, 2, 3].indexOf(2); |
二、優(yōu)化嵌套的條件語句
可優(yōu)化大量的ifelse? switch語句
before:
//method1if (color) {if (color === 'black') {printBlackBackground();} else if (color === 'red') {printRedBackground();} else if (color === 'blue') {printBlueBackground();} else if (color === 'green') {printGreenBackground();} else {printYellowBackground();}} //method2switch(color) {case 'black':printBlackBackground();break;case 'red':printRedBackground();break;case 'blue':printBlueBackground();break;case 'green':printGreenBackground();break;default:printYellowBackground();} //method3switch(true) {case (typeof color === 'string' && color === 'black'):printBlackBackground();break;case (typeof color === 'string' && color === 'red'):printRedBackground();break;case (typeof color === 'string' && color === 'blue'):printBlueBackground();break;case (typeof color === 'string' && color === 'green'):printGreenBackground();break;case (typeof color === 'string' && color === 'yellow'):printYellowBackground();break;}優(yōu)化后
//method4var colorObj = {'black': printBlackBackground,'red': printRedBackground,'blue': printBlueBackground,'green': printGreenBackground,'yellow': printYellowBackground};if (color in colorObj) {colorObj[color]();}?
三、檢查某對象是否有某屬性
使用 hasOwnProperty和in
before:
var myObject = {name: '@tips_js'}; if (myObject.name) { }after:
myObject.hasOwnProperty('name'); // true 'name' in myObject; // true myObject.hasOwnProperty('valueOf'); // false, valueOf 繼承自原型鏈'valueOf' in myObject; // true?
四、更簡單的使用indexOf實現(xiàn)contains功能
before:
var someText = 'javascript rules';if (someText.indexOf('javascript') !== -1) {}after:
!!~someText.indexOf('tex'); // someText contains "tex" - true?
五、將有l(wèi)ength屬性的對象轉(zhuǎn)化為數(shù)組
比如帶有l(wèi)ength屬性的自定義對象,NodeList,parameters等。
//自定義對象var myObj = {length: 3,0: 'a',1:'b',2:'c' };//NodeListvar nodeList = document.querySelectorAll('li');//argumentsfunction test(){if(arguments.length > 0) {} }轉(zhuǎn)化:
//[].slice.call(obj) 或者Array.prototype.slice.call(obj); [].slice.call(nodeList)//es6的Array.from(obj) Array.from(nodeList);?
六、獲取DOM元素在父類中的索引
//html<ul><li></li><li οnclick="getIndex()"></li> </ul>//jsfunction getIndex() {var evt = window.event;var target = evt.target;return [].indexOf.call(document.querySelectorAll('li'), target);// 返回1 }?
轉(zhuǎn)載于:https://www.cnblogs.com/xinyeblog/p/9376594.html
總結(jié)
- 上一篇: C#取整函数Math.Round、Mat
- 下一篇: Remmarguts' Date(POJ