张经纬的博客 -

javascript 序列化

类似php中的serialize方法
BTW:当数据类型是null的时候,由于使用typeof 进行验证,所以会出现问题.(typeof null == “object”) // true

function serialize(_obj)
{
   // Let Gecko browsers do this the easy way
   if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined')
   {
      return _obj.toSource();
   }
 
   // Other browsers must do it the hard way
   switch (typeof _obj)
   {
      // numbers, booleans, and functions are trivial:
      // just return the object itself since its default .toString()
      // gives us exactly what we want
      case 'number':
      case 'boolean':
      case 'function':
         return _obj;
         break;
 
      // for JSON format, strings need to be wrapped in quotes
      case 'string':
         return '\'' + _obj + '\'';
         break;
 
      case 'object':
         var str;
         if (_obj.constructor === Array || typeof _obj.callee !== 'undefined')
         {
            str = '[';
            var i, len = _obj.length;
            for (i = 0; i < len-1; i++) { str += serialize(_obj[i]) + ','; }
            str += serialize(_obj[i]) + ']';
         }
         else
         {
            str = '{';
            var key;
            for (key in _obj) { str += key + ':' + serialize(_obj[key]) + ','; }
            str = str.replace(/\,$/, '') + '}';
         }
         return str;
         break;
 
      default:
         return 'UNKNOWN';
         break;
   }
}

来源:http://blog.stchur.com/2007/04/06/serializing-objects-in-javascript/–Serializing Objects in Javascript

原文链接|

目前 共有 3 条评论 ,点此发表评论

  1. javascript 序列化

    六月 19th, 2011 @ 17:17

    [...] Read this article: javascript 序列化 [...]

  2. yeahxj

    七月 9th, 2011 @ 23:49

    就现阶段来说,javascript的序列化意义并不大。因为现在js的处理都是一种运行时的状态…

    回复

  3. asins

    七月 18th, 2011 @ 15:55

    相比序列化,使用JSON方案我想更好些!

    回复