2013-11-22 31 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

相同的内容,不同的对象。 –

相关问题