當一個面試官問你: JSON都支持什麼對象/類型?你怎麼回答?javascript
也許他的本意是下面這個答案:html
JSON格式支持的數據類型有如下:前端
類型 | 描述 |
---|---|
Number | 在JavaScript中的雙精度浮點格式 |
String | 雙引號的反斜槓轉義的Unicode |
Boolean | true 或 false |
Array | 值的有序序列 |
Value | 它能夠是一個字符串,一個數字,真的仍是假(true/false),空(null )等 |
Object | 無序集合鍵值對 |
Whitespace | 能夠使用任何一對中的令牌 |
null | empty |
但我還真不這麼認爲,我認爲支持任意對象類型,只要是接收容器裏面存在的就能夠。java
能夠使用下面的示例來證實:jquery
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <script src="../resources/js/jquery-1.8.3.min.js"></script> </head> <body></body> </html> <script> function ClassA(sColor) { this.color = sColor; this.sayColor = function() { alert(this.color); }; } function strToJson(str) { var json = eval('(' + str + ')'); return json; } jQuery.ajax({ type : "get", cache : false, dataType : "text", url : "simple.json", success : function(data) { alert(data); var _json = strToJson(data); _json.testcolor.sayColor(); // 這裏是咱們想看的效果 }, error : function() { alert('對不起,服務請求異常!'); } }); </script>
simple.json文件內容:web
{ "retCode": "0000", "retMsg": "Success", "testcolor": new ClassA("red"), "retList": { "le1": { "price": "4800000", "commId": "56761" }, "le2": { "price": "4800000", "commId": "56761" } } }
注意上面代碼裏面的 dataType : "text"面試
由於Jquery源碼裏面是用下面的方式轉換的,咱們須要更加原始的方式,因此我替換成了自定義的strToJson(str)ajax
Jquery源碼:json
// Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } },
其實JSON就是字符串,須要前端進行eval轉換,因此不能簡單的說json支持什麼對象,或者支持什麼數據類型。this
注意提問方式,須要更加嚴謹提出咱們想要提問的問題。