JavaScript常用的经典小技巧

    1、屏蔽鼠标右键 

<--body 方式-->
<body oncontextmenu="window.event.returnValue=false">
</body>
<-- 可用于table-->
<table border oncontextmenu=return(false)>
     <td>no</td>
     <td>no</td>  
 </table>

    2、取消选取,防止复制

<body onselectstart="return false">

     3、不准粘贴

<body onpaste="return false">

     4、检查一段字符串是否全由数字组成   

function checkNum(str){
         return /^d*$/.test(str);
    }
alert(checkNum("1232142141"))    // true
alert(checkNum("123214214a1"))  // false
// 第二种方法

function isNumber(n){
  return !isNaN(parseFloat(n)) && isFinite(n);
}

   5、从数组中随机获取成员

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
    var  randomItem = items[Math.floor(Math.random() * items.length)];
    console.log(randomItem);

    6、生成从0到指定值的数字数组

var numbersArray = [] , max = 10;  
    for( var i=1; numbersArray.push(i++) < max;);  // numbers = [1,2,3 ... 10]
    console.log(numbersArray.join());

   7、打乱数字数组的顺序 

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];  
    numbers = numbers.sort(function(){ return Math.random() - 0.5});
    /* numbers 数组将类似于 [120, 5, 228, -215, 400, 458, -85411, 122205]  */

     8、字符串去空格  

String.prototype.trim = function(){
        return this.replace(/^s+|s+$/g, ""); 
    }
    console.log("**"+("   ceshi    ").trim()+"##");
    // **ceshi##

     9、用JSON来序列化与反序列化 

var person = {name :'xiaoming', age : 22, department : {ID : 15, name : "shichang"} };
    var stringFromPerson = JSON.stringify(person);
    console.log(stringFromPerson)
    /*结果为:"{"name":"xiaoming","age":22,"department":{"ID":15,"name":"shichang"}}"*/
    var personFromString = JSON.parse(stringFromPerson);
    console.log(personFromString)
    /* personFromString 的值与person对象相同 */

    10、使得map()函数方法对数据循环

var squares = [1,2,3,4,5].map(function (val) {  
        return val * val;  
    }); 
     console.log(squares)
   // 结果为: [1, 4, 9, 16, 25]

     11、日期减去天数等于第二个日期

function getDate(date,calDate){
    var a = new Date(date)
    a = a.valueOf()
//    a = a - calDate * 24 * 60 * 60 * 1000  //减天数
    a = a + calDate * 24 * 60 * 60 * 1000  //加天数
    a = new Date(a)
    console.log(a.getFullYear() + "年" + (a.getMonth() + 1) + "月" + a.getDate() + "日")
    }
     getDate("03/31/2016",2)
   /*结果为:2016年4月2日*/ 
原文地址:https://www.cnblogs.com/gzd-123/p/5364096.html