一、屏蔽鼠標右鍵 數組
<--body 方式--> <body oncontextmenu="window.event.returnValue=false"> </body> <-- 可用於table--> <table border oncontextmenu=return(false)> <td>no</td> <td>no</td> </table>
2、取消選取,防止複製dom
<body onselectstart="return false">
3、不許粘貼函數
<body onpaste="return false">
4、檢查一段字符串是否全由數字組成 this
function checkNum(str){ return /^\d*$/.test(str); } alert(checkNum("1232142141")) // true alert(checkNum("123214214a1")) // false
// 第二種方法
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}spa
5、從數組中隨機獲取成員prototype
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到指定值的數字數組code
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、字符串去空格 blog
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日*/