請問,我有麻煩消化一些代碼塊,我真的很感激,如果有人可以幫我一條線,我真的很困惑。我沒有其他人要問!!!!!typeof extend教程,困惑,請幫我理解
下面是代碼故障:
<div id="log"></div> <!-- This is just a container div for the result -->
<script>
//Declare first object, object literal notation:
var object1 = {
apple: 0,
banana: { weight: 52, price: 100 },
cherry: 97
};
//Declare Second object, object literal notation:
var object2 = {
banana: { price: 200 },
durian: 100
};
// Merge object2 into object1
$.extend(object1, object2);
//This is were I am confused, why test for **typeof JSON**?
//Won't it always return "object"? My understanding is that JSON here is just a keyword,
//so typeof JSON will always return object, so of what use is it?
var printObj = typeof JSON !== "undefined" ? JSON.stringify : function(obj) {
var arr = [];
$.each(obj, function(key, val) {
var next = key + ": ";
next += $.isPlainObject(val) ? printObj(val) : val;
arr.push(next);
});
return "{ " + arr.join(", ") + " }";
};
//Here they called printObj as a function passing object1, but how is **object 1** being used,
//when the first statement in printObj is typef JSON?
$("#log").append(printObj(object1));
</script>
因此,在本質我無法理解的條件的typeof JSON怎麼什麼用處,因爲它總是返回「對象」。我也是有無法理解呼叫printObj(object1),以及如何參數object1適合在與printObj時的第一件事有的typeof JSON。
嗚呼!非常感謝你,現在它非常有意義。我只是停留在JSON類型上,但是通過對瀏覽器支持的解釋,它確實將所有內容放在了角度,我可以看到爲什麼要對它進行測試。 – Charles 2014-09-20 22:32:35