Created
April 10, 2013 07:59
-
-
Save cloudchen/5352689 to your computer and use it in GitHub Desktop.
stringify javascript variable
>> It's useful when you want write javascript variable into html template
>> It's much better than JSON.stringify() since that doesn't support stringify function data type
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
function stringify(obj, variable) { | |
var objLiteral = ''; | |
if (typeof obj == 'object') { | |
objLiteral += variable + "="; | |
if (obj.constructor == Array) { | |
objLiteral += "[];\n"; | |
} else { | |
objLiteral += "{};\n"; | |
} | |
for (var item in obj) { | |
if (typeof obj[item] == 'object') { | |
objLiteral += stringify(obj[item], variable + "['" + item + "']"); | |
} else if (typeof obj[item] == 'function') { | |
objLiteral += variable + "['" + item + "'] = " + obj[item].toString() + ";\n" | |
} else if (typeof obj[item] == 'string') { | |
objLiteral += variable + "['" + item + "'] = '" + obj[item].toString() + "';\n" | |
} else { | |
objLiteral += variable + "['" + item + "'] = " + obj[item].toString() + ";\n"; | |
} | |
} | |
} else if(typeof obj == "string") { | |
objLiteral += variable + "='" + obj.toString() + "';\n"; | |
} else { | |
objLiteral += variable + "=" + obj.toString() + ";\n"; | |
} | |
return objLiteral; | |
} |
It supports primitive data type
var a = stringify(function(asd,bb){asd}, 'config');
console.log(a);
var a = stringify("asdf", 'config');
console.log(a);
var a = stringify(12, 'config');
console.log(a);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
transfer complicated variable into its literal type
This is how the result look like