基于获取某输入框的 value 值,格式也许是对象的格式,但 typeof() 之后发现还是字符串的形式,所以在此其中,需要对字符串进一步的格式化为对象。
1、简单粗暴的方法,通过 eval 转化
- var str = '{"hello":"string"}';
- alert(typeof(str));
- str = eval("("+str+")");
- alert(typeof(str));
当然,传闻是不安全的,红皮书《JavaScript高级程序设计》也聊到不建议使用 eval 进行直接的对象操作。
2、推荐这个,更简单,通过内置 JSON 函数 parse() 转化
- var str = '{"hello":"string"}';
- alert(typeof(str));
- str = JSON.parse(str);
- alert(typeof(str));
3、或者先把字符串序列化以后,再进行转化
- var str = JSON.parse(
- JSON.stringify({
- "hello":"string"
- })
- );
- alert(typeof(str));
参考:
https://stackoverflow.com/questions/1086404/string-to-object-in-js
http://bbs.csdn.net/topics/320112068
评论 (0)