經常使用javascript代碼片斷集錦

經常使用方法的封裝

根據類名獲取DOM元素

 1 var $$ = function (className, element) { 
 2     if (document.getElementsByClassName) { 
 3         return (element || document).getElementsByClassName(className); 
 4     }
 5     var nodes = (element || document).getElementsByTagName('*'),
 6     elements = [], 
 7     len = nodes.length, 
 8     i, 
 9     j, 
10     currentNode, 
11     classNames, 
12     classLength; 
13     for (i = 0; i < len; i++) {
14          currentNode = nodes[i]; 
15          classNames = currentNode.className.split(' '); 
16          classLength = classNames.length;
17          for (j = 0 ; j < classLength; j++) {
18              if (classNames[j] === className) { 
19                  elements.push(currentNode); 
20                  break; 
21              } 
22          } 
23     } 
24     return elements; 
25 }

判斷是不是數字

1 function isNum (numStr) {
2                         
3     // 方法一:正則
4     // return /^\d+$/g.test(numStr); 
5 
6     // 方法二:使用isNaN函數,可能存在潛在問題
7     return !isNaN(numStr);
8 }

從數組中刪除指定下標的元素

聲明一個臨時數組,遍歷原數組並判斷是否等於給出的索引,若是相等則跳過本次循環;不然將其壓入臨時數組。javascript

/** * 從數組中刪除指定下標的元素(返回的是新的數組並不影響原來的數組) */
 1 function deleteElement (index,arr) {
 2     
 3     var content = [];
 4     for (var i = 0; i < arr.length; i++) {
 5         if(index == i){
 6             continue;
 7         }
 8         content.push(arr[i]);
 9     }
10     return content;
11 }

經常使用效果案例

標題欄跑馬燈

 1 // 標題欄實現跑馬燈效果(可指定方向left,right)
 2 var marqueeTitle = function(dir){
 3 
 4         var title = document.title;
 5 
 6         var firstCh,leftChs,lastCh;    // 第一個字符,剩下的字符和最後一個字符
 7 
 8         if(dir == 'left'){
 9             firstCh = title.charAt(0);
10             leftChs = title.substring(1,title.length);
11             document.title = leftChs + firstCh;
12         } else if(dir == 'right'){
13             lastCh = title.charAt(title.length - 1);
14             leftChs = title.substring(0,title.length - 1);
15             document.title = lastCh + leftChs;
16         } else {
17             console.error('跑馬燈的方向只能是left和right');
18             return;
19         }
20         // console.log('當前文字的移動方向' + dir + ',' + document.title);
21 }
22 
23 window.onload = function(){
24     // 標題欄跑馬燈(注意帶參的函數應該使用引號)
25     setInterval('marqueeTitle("right")',500);
26 }

走動的頁面時鐘

 1 /**
 2  * 當時鍾數字不足2位數時補0
 3  */
 4 function checkTime(i) {
 5     return i < 10 ? '0' + i : i;
 6 }
 7 
 8 /**
 9  * 走動的頁面時鐘
10  */
11 function timeDate(){
12 
13     var now = new Date(),
14 
15         year = now.getFullYear(),
16         month = now.getMonth() + 1,
17         day = now.getDate(),
18         h = checkTime(now.getHours()),
19         m = checkTime(now.getMinutes()),
20         s = checkTime(now.getSeconds()),
21         weekday = '星期' + '日一二三四五六'.charAt(now.getDay());
22 
23     getDOMById('time').innerHTML =  year + "年" + month + "月" + day + "日 " + weekday + h + ":" + m + ":" + s;
24 
25     setTimeout(timeDate,1000);
26 }
27 
28 window.onload = function(){
29     timeDate();
30 }

抽籤程序

 1 <button id="select">抽籤</button>
 2 <script>
 3     /**
 4      * 從數組中刪除指定下標的元素(返回的是新的數組並不影響原來的數組)
 5      */
 6     function deleteElement (index,arr) {
 7         
 8         var content = [];
 9         for (var i = 0; i < arr.length; i++) {
10             if(index == i){
11                 continue;
12             }
13             content.push(arr[i]);
14         }
15         return content;
16     }
17 
18     var data = [
19             {"no":1,"name":'張三'},
20             {"no":2,"name":'李四'},
21             {"no":3,"name":'王五'},
22             {"no":4,"name":'趙六'},
23             {"no":5,"name":'孫七'}
24         ];
25 
26     console.info(data);
27     var tmp = data;
28     document.getElementById('select').onclick = function (){
29         content = deleteElement(Math.floor(Math.random() * tmp.length),tmp);
30         tmp = content;
31         console.log(content);
32 
33     };
34 </script>

跳出$.each()遍歷使用return false

1 $.each(arr, function(index, val) {
2     console.log(index + '-->' + val);
3     if (index == 2) {
4         return false; // 只能是return false
5     };
6 });

Excel列編號轉化爲數字

 1 /**
 2  * 將excel列轉化爲數字:A-->1,B-->2,AA-->27
 3  */
 4 function convertColNumToInt(sHex) {
 5     
 6     const START = 'A'.charCodeAt(0) - 1;
 7     const RADIX = 26;
 8     var ret = 0;
 9     for(let i = 0;i < sHex.length;i++){
10         ret *= RADIX;
11         ret += sHex.charCodeAt(i) - START;
12     } 
13     return ret;
14 } 
15 
16 // 法2
17 /**
18  * 將excel列轉化爲數字:A-->1,B-->2,AA-->27
19  *
20  * hash表存放
21  * A => 1,B => 2,...Z => 26
22  */
23 function convertColNumToInt(sHex) {
24     
25     const RADIX = 26;
26     let m = new Map();
27     for(let i = 1;i <= 26;i++){
28         m.set(String.fromCodePoint(64+i),i);
29     }
30 
31     let ret = 0;
32     for(let i = 0;i < sHex.length;i++){
33         ret *= RADIX;
34         ret += m.get(sHex.charAt(i));
35     } 
36     return ret;
37 } 

判斷2個數組是否類似

具體需求以下:java

  • 數組中的成員類型相同,順序能夠不一樣。例如[1, true] 與 [false, 2]是類似的。node

  • 數組的長度一致。web

  • 類型的判斷範圍,須要區分:String, Boolean, Number, undefined, null, 函數,日期, window.算法

 1 function arraysSimilar(arr1, arr2) {
 2 
 3     if (!Array.isArray(arr1) || !Array.isArray(arr2) || arr1.length !== arr2.length) {
 4         return false;
 5     }
 6     var t1 = [],
 7         t2 = [];
 8     // 依次取得2個數組中的元素類型並放入新的數組    
 9     for (var i = 0; i < arr1.length; i++) {
10         t1.push(typeOf(arr1[i]));
11         t2.push(typeOf(arr2[i]));
12     }
13     // 排序
14     t1.sort();
15     t2.sort();
16     // 比較排序後序列化的字符串
17     return t1.join() === t2.join();
18 }
19 
20 /**
21  * 獲得元素的類型
22  *
23  * 單獨判斷null主要是兼容低版本IE
24  */
25 function typeOf(element) {
26     return null === element ? "[object Null]" : Object.prototype.toString.call(element);
27 }

對象克隆

基本思路是逐個枚舉屬性,若是屬性是對象,則進行遞歸處理。express

 1 Object.prototype.clone = function() {
 2     var newObj = {};
 3     for(var i in this){
 4         if(typeof(this[i]) == 'object' || typeof(this[i] == 'function')){
 5             newObj[i] = this[i].clone();
 6         } else {
 7             newObj[i] = this[i];
 8         }
 9     }
10     return newObj;
11 }
12 
13 Array.prototype.clone = function() {
14     var newArr = [];
15     if(typeof(this[i]) == 'object' || typeof(this[i]) == 'function'){
16         newArr[i] = this[i].clone();
17     } else {
18         newArr[i] = this[i];
19     }
20     return newArr;
21 }
22 
23 Function.prototype.clone = function() {
24     var _this = this;
25     var newFunc = function () {
26         return _this.apply(this, arguments);
27     };
28     for(var i in this){
29         newFunc[i] = this[i];
30     }
31     return newFunc;
32 }

上面的代碼在絕大多數狀況下有效,可是當2個對象互相引用的時候就顯得無力,會陷入死循環。必須使用圖論算法創建拓撲關係,依次複製每一個節點並重建依賴關係!數組

遞歸刪除目錄及文件

 1 // rmdir -r
 2 var rmdir = function(dir) {
 3   var list = fs.readdirSync(dir);
 4   for (var i = 0; i < list.length; i++) {
 5     var filename = path.join(dir, list[i]);
 6     var stat = fs.statSync(filename);
 7     if (filename === "." || filename === "..") {} else if (stat.isDirectory()) {
 8       rmdir(filename);
 9     } else {
10       fs.unlinkSync(filename);
11     }
12   }
13   fs.rmdirSync(dir);
14 };

複製項目模板文件到指定目錄

 1 function copy(origin, target) {
 2   if(!fs.existsSync(origin)) {
 3     abort(origin + 'does not exist.');
 4   }
 5   if(!fs.existsSync(target)) {
 6     mkdir(target);
 7     console.log('   create : '.green + target);
 8   }
 9   fs.readdir(origin, function(err, datalist) {
10     if(err) {
11       abort(FILEREAD_ERROR);
12     }
13     for(var i = 0; i < datalist.length; i++) {
14       var oCurrent = path.resolve(origin, datalist[i]);
15       var tCurrent = path.resolve(target, datalist[i]);
16       if(fs.statSync(oCurrent).isFile()) {
17         fs.writeFileSync(tCurrent, fs.readFileSync(oCurrent, ''), '');
18         console.log('   create : '.green + tCurrent);
19       } else if(fs.statSync(oCurrent).isDirectory()) {
20         copy(oCurrent, tCurrent);
21       }
22     }
23   });
24 }

以上的程序經常使用於項目的初始化,例如express init默認生成了初始文件和項目。app

判斷節點是否包含另外一個節點

 1 function contains(refNode, otherNode){
 2     if (typeof refNode.contains == "function" && (!client.engine.webkit || client.engine.webkit >= 522)){ 
 3          return refNode.contains(otherNode);
 4   } else if (typeof refNode.compareDocumentPosition == "function"){ 
 5          return !!(refNode.compareDocumentPosition(otherNode) & 16);
 6      } else { 
 7           var node = otherNode.parentNode;
 8           do {
 9                if (node === refNode){
10                         return true; 
11                 } else {
12                      node = node.parentNode;
13                 } 
14           } while (node !== null);     
15           return false;
16      }
17 }

頁面失去焦點觸發標題欄切換

 1 'use strict'
 2 
 3 let originTitile = document.title
 4 let timer;
 5 document.addEventListener('visibilitychange', function () {
 6     if (document.hidden) {
 7         document.title = "(つェ⊂)趕快回來玩遊戲啦"
 8         clearTimeout(timer);
 9     } else {
10         document.title = '(*´∇`*) 歡迎回來繼續遊戲 ' + originTitile
11         timer = setTimeout(function () {
12             document.title = OriginTitile
13         }, 3000)
14     }
15 })
相關文章
相關標籤/搜索