1. 复制N个字符
String.prototype.repeat = function(num){
return (new Array(++num)).join(this);
} var a = 'A';
a.repeat(5); //'AAAAA'
2. 替代if…else…
var result; result = isTrue ? something : anotherthing;
result = something || anotherthing;
result = something && anotherthing;
3. 多条件判断
Maybe:
function yourFun(status){
var color;
switch(status){
case 0:
color = 'white';
break;
case 1:
color = 'red';
break;
case 2:
color = 'yellow';
break;
case 3:
color = 'green';
break;
case 4:
color = 'blue';
break;
} return color;
}
Better:
function yourFun(status){
return ['white', 'red', 'yellow', 'green', 'blue'][status]
}
4. 交换数据
var a = 1,
b = 2; a = [b, b = a][0];
.Thinking
保证代码可读性,灵活应用JS代码技巧。一方面提升自己的编码能力,一方面加深对JS的理解。