继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

JavaScript序列化对象

收到一只叮咚
关注TA
已关注
手记 300
粉丝 22
获赞 112
function serialize(obj) {
    var returnVal; 
    if (obj != undefined) {
        switch (obj.constructor) {
            case Array:
                var vArr = "[";
                for (var i = 0; i < obj.length; i++) 
                {
                    if (i > 0) vArr += ",";
                    vArr += serialize(obj[i]);
                }
                 vArr += "]"
                 return vArr;
            case String:
             returnVal = escape("'" + obj + "'");
                     return returnVal;
            case Number:
             returnVal = isFinite(obj) ? obj.toString() :
                  null;
                 return returnVal;
            case Date: returnVal = "#" + obj + "#";
                 return returnVal;
            default:
                 if (typeof obj == "object")
               {
                   var vobj = []; for (attr in obj) 
                    {
                        if (typeof obj[attr] != "function")
                         {
                            vobj.push('"' + attr + '":' + serialize(obj[attr]));
                         }
                    }
                    if (vobj.length > 0) 
                    return "{" + vobj.join(",") + "}";
                    else return "{}";
                }
                else 
                {
                    return obj.toString();
                } 
        }
    }
     return null;
}


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP