Last active
June 10, 2016 17:21
-
-
Save mgttt/ac10739325e0a0845ed377c18dae1c19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
tested with even IE6 | |
```javascript | |
var o2s= | |
function(o){ | |
if(null==o)return "null"; | |
f=arguments.callee; | |
t=typeof o; | |
if('object'==t){if(Array==o.constructor)t='array';else if(RegExp==o.constructor)t='regexp';} | |
switch(t){ | |
case 'undefined':case 'unknown':return; | |
case 'function':return !('prototype' in o)?"function(){}":(""+o);break; | |
case 'boolean':case 'regexp':return o.toString(); break; | |
case 'number':return isFinite(o)?o.toString():'null';break; | |
case 'string':return '"'+o.replace(/(\\|\")/g,"\\$1").replace(/\n/g,"\\n").replace(/\r/g,"\\r")+'"';break; | |
case 'object':var r=[];try{for(var p in o){v=f(o[p]);if(v!==undefined)r.push('"'+p+'":'+v);}}catch(e){}; | |
return '{'+r.join(',')+'}';break; | |
case 'array':var r=[]; | |
if(o.length>=0){ | |
for(var i=0;i<o.length;i++){var v=f(o[i]);if (v!==undefined)r.push(v);};return '['+r.join(',')+']'; | |
} | |
else{ | |
for(var k in o){var v=f(o[k]);if(v!==undefined)r.push('"'+k+'":'+v);};return '{'+r.join(',')+'}'; | |
} | |
} | |
}; | |
var s2o=function(s){try{return(new Function('return '+s))();}catch(ex){}}; | |
``` | |
```html | |
<script> | |
s=o2s({r:/^xx$/,s:"中文\"\'efg\n回车\r",a:[{},[2,3]]}) | |
try{ | |
document.writeln(s); | |
alert(s); | |
}catch(ex){ | |
console.log(s); | |
console.log(s2o(s)); | |
} | |
</script> | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment