DIV CSS 佈局教程網

JavaScript 常用 API 與工具函數大全(數組、DOM、日期、字符串、校驗)
編輯:關於JavaScript     

這篇文章把自己平時翻得最多的一批 JavaScript 基礎 API 和工具函數整理成一份速查表,涵蓋數組、DOM、數值、日期、字符串、數學運算、浏覽器判斷、面向對象以及表單校驗等,寫業務時直接抄就行。

1. 數組 API

 // 定義數組
 var pageIds = new Array();
 pageIds.push('A');
 pageIds.length;

 // shift:刪除第一項並返回該元素,數組為空返回 undefined
 var a = [1,2,3,4,5]; var b = a.shift();   // a:[2,3,4,5]  b:1

 // unshift:把參數添加到開頭並返回新長度
 var a = [1,2,3,4,5]; var b = a.unshift(-2,-1);  // a:[-2,-1,1,2,3,4,5]  b:7
 // 注意:IE6 下返回值恆為 undefined,FF2 下返回 7,所以這個返回值不可靠,
 // 需要用到返回值時,可以用 splice 代替。

 // pop:刪除最後一項並返回該元素
 var a = [1,2,3,4,5]; var b = a.pop();   // a:[1,2,3,4]  b:5

 // push:把參數添加到末尾並返回新長度
 var a = [1,2,3,4,5]; var b = a.push(6,7);  // a:[1,2,3,4,5,6,7]  b:7

 // concat:返回把參數拼接到原數組後的新數組
 var a = [1,2,3,4,5]; var b = a.concat(6,7);  // b:[1,2,3,4,5,6,7]

 // splice(start, deleteCount, val1, val2...):從 start 刪除 deleteCount 項並插入新值
 var a = [1,2,3,4,5]; var b = a.splice(2,2,7,8,9);  // a:[1,2,7,8,9,5]  b:[3,4]
 a.splice(0,1);              // 等同 shift
 a.splice(0,0,-2,-1);        // 等同 unshift
 a.splice(a.length-1,1);     // 等同 pop
 a.splice(a.length,0,6,7);   // 等同 push

 // reverse:數組反序
 var a = [1,2,3,4,5]; var b = a.reverse();  // a、b 均為 [5,4,3,2,1]

 // sort:排序,可傳比較函數
 var a = [1,2,3,4,5]; var b = a.sort();

 // slice(start, end):截取片段,返回新數組,不改原數組
 var a = [1,2,3,4,5]; var b = a.slice(2,5);  // b:[3,4,5]

 // join(separator):拼接為字符串,默認用逗號分隔
 var a = [1,2,3,4,5]; var b = a.join("|");   // b:"1|2|3|4|5"

2. 最常用 DOM API

 // document 方法
 getElementById(id)            // 返回指定節點
 getElementsByTagName(name)    // 返回匹配元素的集合
 createElement(name)           // 創建元素節點
 createTextNode(text)          // 創建純文本節點
 documentElement               // 返回 html 節點
 document.body                 // 返回 body 節點

 // element 方法
 getAttribute(attributeName)   // 取值
 setAttribute(attributeName, value)  // 賦值
 removeAttribute(attributeName)      // 移除屬性
 getElementsByTagName(name)          // 返回結點內匹配元素的集合

 // node 方法
 appendChild(child)                    // 添加子結點
 removeChild(child)                    // 移除子結點
 replaceChild(newChild, oldChild)      // 替換子結點
 insertBefore(newChild, refChild)      // 在同層級前面插入
 hasChildNodes()                       // 是否有子結點

 // node 屬性
 nodeName / nodeType / nodeValue
 parentNode / childNodes / firstChild / lastChild
 previousSibling / nextSibling

3. 一個 HashMap 實現

 function HashMap() {
     var size = 0;              // Map 大小
     var entry = new Object();  // 存放數據的對象

     this.put = function (key, value) {
         if (!this.containsKey(key)) { size++; }
         entry[key] = value;
     };
     this.get = function (key) {
         return this.containsKey(key) ? entry[key] : null;
     };
     this.remove = function (key) {
         if (this.containsKey(key) && (delete entry[key])) { size--; }
     };
     this.containsKey = function (key) {
         return (key in entry);
     };
     this.containsValue = function (value) {
         for (var prop in entry) { if (entry[prop] == value) { return true; } }
         return false;
     };
     this.values = function () {
         var values = new Array();
         for (var prop in entry) { values.push(entry[prop]); }
         return values;
     };
     this.keys = function () {
         var keys = new Array();
         for (var prop in entry) { keys.push(prop); }
         return keys;
     };
     this.size = function () { return size; };
     this.clear = function () { size = 0; entry = new Object(); };
 }

 var map = new HashMap();
 map.put("A", "1");
 map.put("B", "2");
 alert(map.get("A"));

 // 對象也可以作為 Key,但實際上會自動調用該對象的 toString(),
 // 最終還是以字符串作為 Key。自定義對象需要重寫 toString(),否則會出意外結果:
 function MyObject(name) { this.name = name; }
 map.put(new MyObject("小張"), "小張");
 map.put(new MyObject("小明"), "小明");

4. 數字相關函數

 // 聲明
 var i = 1;
 var i = new Number(1);

 // 字符串與數字互轉
 var i = 1;
 var str = i.toString();    // "1"
 var str = new String(i);   // "1"
 i = parseInt(str);         // 1
 i = parseFloat(str);       // 1.0
 // 注意:parseInt、parseFloat 會把類似 "32G" 的字符串強制轉成 32

 // 判斷是否為有效數字
 if (typeof i == "number") { }
 // parseInt、parseFloat 可能返回 NaN(Not a Number),
 // 但 isNaN 並不完全適合判斷一個字符串是否是數字
 i = parseInt(str);
 if (isNaN(i)) { }

 // 小數取整
 Math.round(1.5);  // 2,四捨五入
 Math.ceil(1.5);   // 2,大於 f 的最小整數
 Math.floor(1.5);  // 1,小於 f 的最大整數

 // 格式化顯示
 (3.14159).toFixed(2);     // "3.14",保留兩位小數
 (3.14159).toPrecision(5); // "3.1415",五位有效數字

 // 進制轉換
 parseInt("0x1f", 16);
 parseInt("11010011", 2);

 // 隨機數
 Math.random();                    // 0-1 之間的小數
 Math.floor(Math.random() * n);    // 0 到 n-1 的整數

5. 一個簡單的堆棧實現

 function stack(){
     if (this.top == undefined) {
         this.top = 0;             // 棧頂指針
         this.unit = new Array();  // 數據存放域
     }
     this.push = function (pushvalue) {
         this.unit[this.top] = pushvalue;
         this.top += 1;
     };
     this.readAllElements = function () {
         if (this.top == 0) { alert("當前棧空,無法讀取數據"); return ""; }
         var outStr = "";
         for (var count = 0; count < this.top; count++) { outStr += this.unit[count] + ","; }
         return outStr;
     };
     this.pop = function () {
         if (this.top == 0) { alert("當前棧空,無法彈出數據"); return ""; }
         var popTo = this.unit[this.top - 1];
         this.top--;
         return popTo;
         // 這裡只做了指針減一,沒有真正釋放資源,數據仍在數組中,只是無法訪問。
     };
 }

6. 日期函數

 // 聲明
 var myDate = new Date();                                  // 當前時間
 var myDate = new Date(yyyy, mm, dd, hh, mm, ss);
 var myDate = new Date("monthName dd, yyyy hh:mm:ss");
 var myDate = new Date(epochMilliseconds);

 // 獲取各部分的時間
 myDate.getYear();            // 兩位年份
 myDate.getFullYear();        // 完整年份
 myDate.getMonth();           // 月份,0-11,0 代表 1 月
 myDate.getDate();            // 日,1-31
 myDate.getDay();             // 星期,0-6,0 代表週日
 myDate.getTime();            // 從 1970.1.1 起的毫秒數,即時間戳
 myDate.getHours();           // 小時,0-23
 myDate.getMinutes();         // 分鐘,0-59
 myDate.getSeconds();         // 秒,0-59
 myDate.getMilliseconds();    // 毫秒,0-999
 myDate.toLocaleDateString(); // 當前日期
 myDate.toLocaleTimeString(); // 當前時間
 myDate.toLocaleString();     // 日期與時間

 // 計算之前或之後的時間:以 set 開頭的方法,用法與 get 基本一致
 myDate.setDate(myDate.getDate() + 10);   // 加 10 天

 // 檢查有效日期(只允許 mm-dd-yyyy 或 mm/dd/yyyy)
 if (checkDate("2006-01-01")) { }
 // 正則校驗 yyyy-mm-dd / yy-mm-dd / yyyy/mm/dd / yy/mm/dd
 var r = /^(\d{2}|\d{4})[\/-]\d{1,2}[\/-]\d{1,2}$/;
 if (r.test(myString)) { }

7. 字符串 API

 // 聲明
 var myString = new String("Every good boy does fine.");
 var myString = "Every good boy does fine.";

 // 拼接
 var myString = "Every " + "good boy " + "does fine.";
 myString += "good boy does fine.";

 // 截取
 "Every good boy does fine.".substring(6);    // 從第 6 位到末尾:"good boy does fine."
 "Every good boy does fine.".substring(0,10); // "Every good"
 "Every good boy does fine.".slice(11,-6);    // "boy does",支持負數索引
 "Every good boy does fine.".substr(6,4);     // "good",指定長度

 // 大小寫轉換
 "Hello".toLowerCase();  // "hello"
 "Hello".toUpperCase();  // "HELLO"

 // 比較
 var aString = "Hello!";
 var bString = new String("Hello!");
 aString == "Hello!";    // true
 aString == bString;     // true
 aString === bString;    // false,兩個對象不同,盡管值相同

 // 檢索
 "hello everybody.".indexOf("every");  // 找不到返回 -1,找到返回起始位置

 // 替換
 "I is your father.".replace("is","am");  // "I am your father."

 // 特殊字符
 // \b 後退符  \t 水平制表符  \n 換行符  \v 垂直制表符
 // \f 分頁符  \r 回車符  \" 雙引號  \' 單引號  \\ 反斜桿

 // Unicode 編碼互轉
 "hello".charCodeAt(3);        // "l" 的 Unicode 編碼
 String.fromCharCode(66);      // Unicode 為 66 的字符

 // URL 編碼
 encodeURI("hello all");       // "hello%20all"
 decodeURI(code);              // "hello all"
 encodeURIComponent(); decodeURIComponent();  // 對應的一組

8. Math 對象

 Math.abs(num)      // 絕對值
 Math.acos(num)     // 反余弦
 Math.asin(num)     // 反正弦
 Math.atan(num)     // 反正切
 Math.atan2(y, x)   // y/x 的反正切
 Math.ceil(num)     // 大於 num 的最小整數
 Math.cos(num)      // 余弦
 Math.exp(x)        // e 的 x 次冪
 Math.floor(num)    // 小於 num 的最大整數
 Math.log(num)      // 自然對數
 Math.max(num1, num2)  // 較大值
 Math.min(num1, num2)  // 較小值
 Math.pow(x, y)     // x 的 y 次方
 Math.random()      // 0 到 1 之間的隨機數
 Math.round(num)    // 四捨五入
 Math.sin(num)      // 正弦
 Math.sqrt(num)     // 平方根
 Math.tan(num)      // 正切
 Math.PI            // 3.141592653589793
 Math.E             // 2.718281828459045

9. 浏覽器與環境判斷

 var browserName = navigator.appName;      // "Microsoft Internet Explorer" / "Netscape"
 var browserVersion = navigator.appVersion;

 var isWin  = (navigator.userAgent.indexOf("Win") != -1);
 var isMac  = (navigator.userAgent.indexOf("Mac") != -1);
 var isUnix = (navigator.userAgent.indexOf("X11") != -1);

 // 判斷是否支持某對象、方法、屬性
 if (document.images) { }
 if (document.getElementById) { }

 // 當前語言
 if (navigator.userLanguage) { var l = navigator.userLanguage.toUpperCase(); }

 // 是否支持 Cookies
 if (navigator.cookieEnabled) { }

10. 用 call 實現繼承

 // 動物類
 function animal(bSex){
     this.sex = bSex;
     this.getSex = function(){ return this.sex; };
 }
 animal.SEX_G = new Object();  // 雌性
 animal.SEX_B = new Object();  // 雄性

 // 子類:鳥
 function bird(bSex){
     animal.call(this, bSex);
     this.fly = function(iSpeed){ alert("飛行時速高達 " + iSpeed); };
 }
 // 子類:魚
 function fish(bSex){
     animal.call(this, bSex);
     this.swim = function(iSpeed){ alert("游動時速高達 " + iSpeed); };
 }
 // 雜交品種
 function crossBF(bSex){
     bird.call(this, bSex);
     fish.call(this, bSex);
 }

 var oPet = new crossBF(animal.SEX_G);
 alert(oPet.getSex() == animal.SEX_G ? "雌性" : "雄性");
 oPet.fly(124);
 oPet.swim(254);

11. 面向對象的組織方式

 MyTool = new function(){
     /**
      * 返回非空字符串,如果是空的且有默認值就返回默認值
      */
     this.notNull = function(str, defaultStr){
         if (typeof(str) == "undefined" || str == null || str == '') {
             return defaultStr ? defaultStr : '';
         } else {
             return str;
         }
     };
 };
 rootId = MyTool.notNull(rootId, '001000');

12. 常用工具與表單校驗函數

 /** JSON 對象轉字符串 */
 function jsonObj2Str(json) {
     var str = "{";
     for (prop in json) { str += prop + ":" + json[prop] + ","; }
     str = str.substr(0, str.length - 1);
     return str + "}";
 }
 /** JSON 字符串轉對象 */
 function jsonStr2Obj(jsonstr) { return eval("(" + jsonstr + ")"); }

 /** 獲得元素的 left 坐標 */
 function getLeft(e){
     var offset = e.offsetLeft;
     if (e.offsetParent != null) offset += getLeft(e.offsetParent);
     return offset;
 }
 /** 獲得元素的 top 坐標 */
 function getTop(e){
     var offset = e.offsetTop;
     if (e.offsetParent != null) offset += getTop(e.offsetParent);
     return offset;
 }
 /** 刪除字符串左右空格 */
 function trim(str) { return str.replace(/(^\s*)|(\s*$)/g, ""); }

 /** 根據 id 取元素 */
 function $(str) { return document.getElementById(str); }
 /** 根據 name 取第一個元素 */
 function $byName(str) {
     var arr = document.getElementsByName(str);
     return arr ? arr[0] : null;
 }

 /** 返回非空字符串,可帶默認值 */
 function notNull(str, defaultStr) {
     if (typeof(str) == "undefined" || str == null || str == '') {
         return defaultStr ? defaultStr : '';
     }
     return str;
 }
 /** 比較兩個日期大小 */
 function compareTwoDate(smallDate, bigDate, msg) {
     var v1 = $(smallDate).value, v2 = $(bigDate).value;
     if (v1 >= v2) { alert(msg); $(bigDate).focus(); return false; }
     return true;
 }
 /** 比較兩個金額大小 */
 function compareTwoNum(smallNum, bigNum, msg) {
     var v1 = $(smallNum).value, v2 = $(bigNum).value;
     if (parseFloat(v1) >= parseFloat(v2)) { alert(msg); $(bigNum).focus(); return false; }
     return true;
 }
 /** 檢查文本框長度是否超限,一個漢字算兩位 */
 function checkLength(textId, len, msg) {
     var obj = $(textId);
     var str = obj.value.replace(/[^\x00-\xff]/g, "**");
     if (str.length > len) {
         alert("[" + msg + "]長度最大為" + len + "位,請重新輸入!\n注意:一個漢字占2位。");
         obj.focus();
         return false;
     }
     return true;
 }
 /** 判斷文本框不能為空 */
 function checkIfEmpty(textId, msg) {
     var obj = $(textId);
     if (trim(obj.value) == '') {
         alert('[' + msg + ']不得為空!');
         obj.focus();
         return false;
     }
     return true;
 }
 /** 判斷是否為郵箱 */
 function checkIsMail(textId, msg) {
     var obj = $(textId);
     if (!_isEmail(obj.value)) {
         alert('[' + msg + ']不是合法的郵件地址!');
         obj.focus();
         return false;
     }
     return true;
 }
 function _isEmail(strEmail) {
     if (strEmail.indexOf('@') == -1) { return false; }
     var first = strEmail.indexOf('.');
     var tempStr = strEmail.substring(first + 1);
     if (tempStr.indexOf('.') != -1) { return false; }
     if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
         return true;
     }
     return false;
 }
 /** 判斷是否為數字 */
 function checkIsNum(textId, msg) {
     var obj = $(textId);
     if (isNaN(obj.value)) {
         alert('[' + msg + ']必須為數字。');
         obj.focus();
         return false;
     }
     return true;
 }
 /** 判斷是否含有非法字符 */
 function checkIsValid(textId, msg) {
     var obj = $(textId);
     if (!_isValidString(obj.value, '[' + msg + ']不得含有非法字符。')) {
         obj.focus();
         return false;
     }
     return true;
 }
 function _isValidString(szStr, errMsg) {
     var voidChar = "'\"><`~!@#$%^&()()!¥……?“”‘'*";
     for (var i = 0; i < voidChar.length; i++) {
         if (szStr.indexOf(voidChar.substring(i, i + 1)) > -1) {
             alert(errMsg);
             return false;
         }
     }
     return true;
 }

 /* ------- 下拉菜單相關 ------- */
 /** 校驗下拉菜單已選(空值默認為 -1) */
 function checkChooseSelect(selectId, msg, nullValue) {
     var obj = $(selectId);
     if (obj.value == notNull(nullValue, '-1')) {
         alert('[' + msg + ']必選!');
         obj.focus();
         return false;
     }
     return true;
 }
 /** 取得下拉菜單顯示的文本 */
 function getSelectText(selectObj) {
     return selectObj.options[selectObj.selectedIndex].text;
 }
 /** 取得下拉菜單的值 */
 function getSelectValue(selectObj) {
     return selectObj.options[selectObj.selectedIndex].value;
 }
 /** 設置下拉菜單的選中值 */
 function setSelectValue(obj, value) { obj.value = value; }
 /** 根據 "1,男;2,女;3,未知" 這樣的鍵值串組裝下拉菜單 */
 function setSelectContent(obj, valAndText){
     if (trim(valAndText) == '') { alert('沒有要進行組裝下拉菜單的數據!'); return false; }
     clearSelect(obj);
     var keyandvalues = valAndText.split(';');
     for (var i = 0; i < keyandvalues.length; i++) {
         var arr = keyandvalues[i].split(',');
         if (arr) { obj.add(new Option(arr[1], arr[0])); }
     }
 }
 /** 清空下拉菜單 */
 function clearSelect(obj) {
     for (var i = obj.options.length; i > 0; i--) { obj.remove(0); }
 }

 /* ------- 多選框相關 ------- */
 /** 返回選中的 checkbox 的 value,逗號隔開 */
 function getCheckedIds(checks){
     var selectedValue = '';
     for (var index = 0; index < checks.length; index++) {
         if (checks[index].checked == true) { selectedValue += checks[index].value + ","; }
     }
     if (selectedValue.length > 0) return selectedValue.substring(0, selectedValue.length - 1);
     return selectedValue;
 }

13. 校驗方法的調用示例

把上面的 js 引入頁面,然後這樣串起來用:

 /** 表單校驗示例:短路與,任意一項不通過就返回 false */
 function check(){
     if (checkIfEmpty('a','非空校驗')
         && checkIsMail('b','郵箱校驗')
         && checkIsNum('c','數字校驗')
         && checkIsValid('d','合法性校驗')
         && compareTwoDate('e','f','小日期與大日期關系錯誤!')
         && checkLength('g', 5, '長度校驗')
         && checkChooseSelect('h','下拉菜單非空','-1')
         && compareTwoNum('k','l','大小數目關系不正確!')){
         alert('校驗通過!');
         return true;
     }
     return false;
 }
 /** 取下拉菜單的值和文本 */
 function getSelect(){
     var sss = $('h');
     alert('下拉菜單選擇的文本是:' + getSelectText(sss) + '\n' + '下拉菜單選擇的值是:' + getSelectValue(sss));
 }
 /** 根據鍵值字符串設置下拉菜單內容 */
 function setSelect(){ setSelectContent($('h'), $('i').value); }
 /** 取得多選框選中的 value */
 function getMulti(){ alert('多選選擇的值是:' + getCheckedIds(document.getElementsByName('j'))); }
 <table>
 <tr><td>非空: <input id='a'></td><td>checkIfEmpty('a','非空校驗')</td></tr>
 <tr><td>郵箱: <input id='b' value='323232@2323.com'></td><td>checkIsMail('b','郵箱校驗')</td></tr>
 <tr><td>數字: <input id='c' value='aaaa'></td><td>checkIsNum('c','數字校驗')</td></tr>
 <tr><td>合法字符: <input id='d' value='@$@$#$#!%%#'></td><td>checkIsValid('d','合法性校驗')</td></tr>
 <tr>
   <td>小的日期: <input id='e' value='2010-1-1'> 大的日期: <input id='f' value='2011-1-1'></td>
   <td>compareTwoDate('e','f','小日期與大日期關系錯誤!')</td>
 </tr>
 <tr>
   <td>小的數: <input id='k' value='12.3'> 大的數: <input id='l' value='4564'></td>
   <td>compareTwoNum('k','l','大小數目關系不正確!')</td>
 </tr>
 <tr><td>字符長度校驗(&lt;5): <input id='g'></td><td>checkLength('g',5,'長度校驗')</td></tr>
 <tr>
   <td>下拉菜單非空校驗:
     <select id='h'>
       <option value='-1'>請選擇</option>
       <option value='1'>立項</option>
       <option value='2'>可研</option>
     </select>
   </td>
   <td>checkChooseSelect('h','下拉菜單非空','-1')</td>
 </tr>
 <tr><td colspan='2'><button onclick='check()'>測試表單校驗方法</button></td></tr>
 <tr>
   <td>輸入下拉菜單的鍵值字符串 <input id='i' value='1,男;2,女;3,未知'>
   <button onclick='setSelect()'>設置下拉菜單的值</button></td>
   <td>setSelectContent($('h'), sss)</td>
 </tr>
 <tr>
   <td>
     <input type='checkbox' name='j' value='aaa1'>
     <input type='checkbox' name='j' value='aaa2'>
     <input type='checkbox' name='j' value='aaa3'>
     <input type='checkbox' name='j' value='aaa4'>
     <button onclick='getMulti()'>得到多選選擇的值</button>
   </td>
   <td>getCheckedIds(document.getElementsByName('j'))</td>
 </tr>
</table>

以上就是本文的全部內容,希望大家能夠喜歡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved