2013-11-22 30 views
0

我執行某個函數並獲取返回值。這個值可以是任何東西(字符串,數組,對象,引用,函數)。然後我使用JSON.stringify來傳遞這個結果。Javascript - 確定對象中是否有範圍引用

現在,函數和引用對我們傳遞給它們的範圍並沒有太大的幫助,所以整個「to string,eval」方法並沒有多大用處。我將把它們存儲在本地數組中,並傳遞一個ID以便稍後參考它們。但是,我會繼續發送字符串數據,數組和對象(在javascript對象的「關聯數組」中),因爲這些都與JSON.stringify很好地發揮作用。

我已經在使用try... JSON.stringify() catch來做遞歸對象(其中JSON.stringify錯誤)。但這並不包含上面提到的任何其他內容。

什麼是檢查值是否包含函數的最有效方法?

而且不

typeof foo === "function" 

因爲返回可能是

["foo", "bar", ["foo", "bar"], function(){...something}] 

我不想要麼挑開每個單獨的類型,只是在整個返回是否有任何功能/對象不能安全地串起來。我大概可以研究如何循環和檢查每個單獨的值,但是如果有一個可以想到的快捷方式或更高效的方法,我希望聽到它。

謝謝!

回答

0

精煉歡迎和讚賞!

//your favorite object length checking function could go here 
$.objectLength = (function(){ 
    //ie<9 
    if (typeof Object.keys === "undefined"){ 
     return function(o){ 
      var count = 0, i; 
      for (i in o) { 
       if (o.hasOwnProperty(i)) { 
        count++; 
       } 
      } 
      return count; 
     }; 

     //everyone else 
    } else { 
     return function(o){ 
      return Object.keys(o).length; 
     } 
    } 
})(); 

//comparing our two objects 
$.checkMatch = function(a, b){ 

    //if they're not the same length, we're done here. (functions exist, etc) 
    if (typeof a !== typeof b || typeof a === "object" && typeof b === "object" && a && b && $.objectLength(a) !== $.objectLength(b)){ 
     return false; 

    //if they are the same length, they may contain deeper objects we need to check. 
    } else { 
     var key; 
     for (key in a){ 

      //make sure it's not prototyped key 
      if (a.hasOwnProperty(key)){ 

       //if it doesn't exist on the other object 
       if (!b.hasOwnProperty(key)){ 
        return false; 

       //if this an object as well 
       } else if (typeof a[key] === "object"){ 

        //check for a match 
        if (!$.checkMatch(a[key], b[key])){ 
         return false; 
        } 

       //then check if they're not equal (simple values) 
       } else if (a[key] !== b[key]){ 
        return false 
       } 
      } 
     } 
     return true; 
    } 
}; 
//...stuff 

//catch recursive objects in parameters 
var good = true, sendObject = {"ourobject", "values"}, finalSendObject; 
//try to stringify, which rejects infinitely recursive objects 
try { 
    finalSendObject = JSON.stringify(sendObject); 
} catch(e){ 
    good = false; 
} 
//if that passes, try matching the original against the parsed JSON string 
if (good && sendObject !== JSON.parse(finalSendObject)){ 
    good = $.checkMatch(sendObject, JSON.parse(finalSendObject)); 
} 
-1

這將無法正常工作

但我會離開它的人誰認爲的嘗試它。即將推出工作解決方案。

30秒後,我想出了自己。

將其解析。如果有什麼改變,它不會等於自己。

var checkParse = function(obj){ 
    return obj === JSON.parse(JSON.strigify(obj)); 
} 
+0

返回值將始終爲'false'。 'checkParse({}); // false' –

+0

現在進行測試。你怎麼看?如果它說...一個字符串,然後我將它解析出來,它應該是相同的。 –

+0

相同的內容,不同的對象。 –

相關問題