Javascript toSource then toObject
when toSource method is used to an object ..it will be like this
({name:"myname", value:"myvalue"})
my question is how would you convert it back to object? or rather just access t开发者_如何学编程he properties like
alert(objectName.name);
thus alerting "myname"
Use eval to change it back to an object. alert(eval({name:"myname"}.toSource()).name).
toSource() returns a string, so you can use javascript's .replace() method, passing it a regular expression to strip off the parentheses, and then call JSON.parse() on the resultant string to turn it back into an object.
Like so:
var obj = {name: "myname", value:"myvalue"};
var toSourced = obj.toSource();
var stringObj = toSourced.replace(/\((.*)\)/, "$1");
var objAgain = JSON.parse(stringObj);
alert(objAgain.name);
As a side note, toSource() is not supported by IE or Chrome, and you should avoid it's use as you can turn a JSON object into a string by passing it to JSON.stringify(), which is native in IE8+, Firefox, and Chrome.
加载中,请稍侯......
精彩评论