zyanfei
9/18/2018 - 3:18 AM

js给字符串和对象定义属性

js给字符串和对象定义属性

// 给string定义parse_str属性
String.prototype.parse_str = function(){
//    console.log(this.valueOf());
    var value = this.valueOf();
    var arrRet = {};
    if (value) {
        var arr1 = value.split("&");
        for(var i = 0;i< arr1.length;i++) {
            var arr2 = arr1[i].split("=");
            if (arr2.length> 1) {
                arrRet[arr2[0]] = arr2[1];
            }
        }
        return  arrRet;
    } else {
        return null;
    }
   
};
   
// 给object定义http_build_query属性 
Object.defineProperty(Object.prototype,'http_build_query',{
    value:function() {
        var value = this.valueOf();
        var queryArr = $.map(value,function(v,k){
            return k + '='+v;
        })
        return queryArr.join('&');
    }});