布尔值短写法
true; //Before
!0; //After
串连字符串
''+a+b+c; //before
''.concat(a, b, c);
优化嵌套的条件语句
可优化大量的ifelse switch语句
before:
//method1
if (color) {
if (color === 'black') {
printBlackBackground();
} else if (color === 'red') {
printRedBackground();
} else if (color === 'blue') {
printBlueBackground();
} else if (color === 'green') {
printGreenBackground();
} else {
printYellowBackground();
}
}
//method2
switch(color) {
case 'black':
printBlackBackground();
break;
case 'red':
printRedBackground();
break;
case 'blue':
printBlueBackground();
break;
case 'green':
printGreenBackground();
break;
default:
printYellowBackground();
}
//method3
switch(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;
}
优化后
//method4
var 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实现contains功能
before:
var someText = 'javascript rules';
if (someText.indexOf('javascript') !== -1) {
}
after:
!!~someText.indexOf('tex'); // someText contains "tex" - true
数值取
常规写法:
let num = 1.12;
let intNum = parseInt(num);
高逼格写法:
let num = 1.12;
let intNum;
// 写法一:
intNum = num|0;
// 写法二:
intNum = ~~num;
// 写法三:
intNum = num^0;
// 写法四
intNum = num << 0;
不用第三个参数交换两个变量的数值
常规写法:
let num1 = 5, num2 = 6;
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
// 常规写法二:
num1 ^= num2;
num2 ^= num1;
num1 ^= num2
高逼格写法:(逼格高不高?)
// 写法一:
let num1 = 5, num2 = 6;
num1 = [num2, num2 = num1][0];
// 写法二:
[num1, num2] = [num2, num1];