超級有用的JavaScript函數

jopen 10年前發布 | 13K 次閱讀 JavaScript開發 JavaScript

下面是一些超級有用的JavaScript函數。

將字符串中的第一個字母大寫

這個函數是PHP uctoupper()函數的一個克隆!

 function ucfirst(string) {     return string.charAt(0).toUpperCase() + string.slice(1);
} 

搜索JavaScript 數組和對象集合

提供一個對象或一個對象數組,一個鍵和一個值。然后返回匹配鍵的對象或對象 - 值對。

 function searchObjects(obj, key, val) {     var objects = [];
    for (var i in obj) {
        if (typeof obj[i] == 'object') {
            objects = objects.concat(searchObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
} 

搜索JavaScript對象集合,返回索引位置

通常用它來查找索引,然后就可以直接引用該對象。

 function getObjectIndexFromId(obj, id) {     if (typeof obj == "object") {
        for (var i = 0; i < obj.length; i++) {
            if (typeof obj[i] != "undefined" && typeof obj[i].id != "undefined" && obj[i].id == id) {
                return i;
            }
        }
    }
    return false;
} 

比較JavaScript對象

提供了兩個對象,它會告訴你,它們是否相同。可用于實現表單“更改未保存”的提示非常有用。

function compareObjects(obj1, obj2) {
    for (var param in obj1) {
        if (typeof obj1[param] == 'object' && obj1[param] != null) {
            //If the length is different, we dont need to check if the values have changed (As it is obvious they have!)
            if (typeof obj2[param] != "undefined" && obj1[param].length != obj2[param].length) {
                return true;
            }
            //Return if we have already found evidence of a change, otherwise keep checking the rest of the object
            if (compareObjects(obj1[param], obj2[param]) === true) return true;
        } else {
            //Ignore the angular added $$hashKey variable
            if (param != "$$hashKey") {
                //If the values are different then return true                 if (obj1[param] != obj2[param]) {
                    return true;
                }
            }
        }
    }
    //Once every value has been checked and nothing is different, return false;
    return false;
} 

MySQL的日期時間轉為JavaScript的日期

快速將一個MySQL的日期時間字符串轉換成JavaScript的日期對象。

 function mysqlDateTimeToJSDate(datetime) {     // Split timestamp into [ Y, M, D, h, m, s ]     var t = datetime.split(/[- :]/);
    return new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
} 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!