我执行一些函数并获得返回值。该值可以是任何值(字符串,数组,对象,引用,函数)。然后,我使用JSON.stringify
传递此结果。
现在,函数和引用在它们传递给它的范围方面并没有给我带来太多好处,所以整个“to string,eval”方法并没有多大用处。我将把它们存储在一个本地数组中,然后传递一个ID以便稍后引用它们。但是,我确实继续发送字符串数据,数组和对象(在javascript对象的“关联数组”意义上),因为它们与JSON.stringify
非常匹配。
我已经使用try... JSON.stringify() catch
对递归对象执行此操作(JSON.stringify
错误。)但这并不能解释上面提到的任何其他内容。
检查值是否包含函数的最有效方法是什么?
而不是
typeof foo === "function"
因为返回可能是
["foo", "bar", ["foo", "bar"], function(){...something}]
我不想拆开每个单独的部分类型,只是返回整个是否有任何无法安全字符串化的函数/对象。我可能会弄清楚如何循环和检查每个单独的值,但如果有一个人可以想到的快捷方式或更有效的方法,我想听听它。
谢谢!
答案 0 :(得分: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 :(得分:-1)
这不起作用
但我会把它留给那些想要尝试它的人。工作解决方案即将推出
30秒后,我自己弄清楚了。将其串起来,解析它。如果有任何改变,它就不会与自己相等。
var checkParse = function(obj){
return obj === JSON.parse(JSON.strigify(obj));
}