JavaScript奇淫技巧

  • 打乱数组
var a=[1,2,3,4,5,6,7,8];
function change(arr){
    var NewArr = arr.sort(function(){Math.random()-0.5});//正负交替出现
    return NewArr;
}
  • 返回结果ture是-1或者false是0
~"haha".indexOf("h");
>>-1
~"haha".indexOf("e");
>>0
~"hagha".indexOf("g");
>>-1
  • 返回数组中某一个值
var a=["a","b","c","d","e"];
console.log(a[~~(Math.random()*a.length)]);
//方法一,位运算符~的实现
["a","b","c","d","e"][Math.floor(Math.random()*5)]
//方法二,Math.floor()方法
  • js操作表单(单选框)
var timeForm = radiobox.getElementsByTagName('input');
for (var i = 0; i < timeForm.length; i++) {    
      if (timeForm[i].checked) {        
            pageState.nowGraTime = timeForm[i].value;  
      }
}//这样OK
var timeForm = radiobox.getElementsByTagName('input');
for (var i = 0; i < timeForm.length; i++) {    
      if (timeForm[i].getAttribute(checked)) {        
            pageState.nowGraTime = timeForm[i].value;  
      }
}//这样NO

原因:
getAttribute获取checkbox或者radio的checked值在各个浏览器不同。
E6/7 :依次返回 false/true
IE8 :依次返回 空字符串/checked
IE9/10/Firefox/Safari/Chrome/Opera :依次返回 null/空字符串

  • 高逼格代码(两段代码作用相同,换位判断是否变号)
var swip = function (turnleft) { //0 是 false   
         var r = (turnleft ? !!direction[0] : !!direction[1]) ? -1 : 1;  
         direction[0] += direction[1];    
         direction[1] = direction[0] * r - direction[1] * r;      
         direction[0] = direction[0] * r - direction[1];    
         angle += turnleft ? -90 : 90;    
         block.style.transform = "rotate(" + angle + "deg)";
};
var swipa = function (turnleft) {    
         var r;    
         if (turnleft) {        
               r = ( !!direction[0] ) ? -1 : 1;   
         } else {       
              r = ( !!direction[1]) ? -1 : 1;    
         }   
         var c;    
         c = direction[0];   
         direction[0] = direction[1] * r;    
         direction[1] = c * r;    
         angle += turnleft ? -90 : 90;   
         block.style.transform = "rotate(" + angle + "deg)";
};

你可能感兴趣的:(JavaScript奇淫技巧)