开发者

Javascript toSource then toObject

开发者 https://www.devze.com 2023-01-26 15:56 出处:网络
when toSource method is used to an object ..it will be like this ({name:\"myname\", value:\"myvalue\"})

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消