【发布时间】:2017-07-27 02:03:23
【问题描述】:
我正在尝试使用递归复制 JSON.stringify()。我有点困惑为什么我在返回的 JSON 字符串中没有定义。这是我到目前为止所做的:
var testobj = {num:123,str:"This is a string",bool:true,o:{x:1,y:2},iamnull:null}
var count = 0
var stringifyJSON = function(obj) {
// your code goes here
if(obj === undefined){
return console.log("obj was undefined");
}
count = count + 1
if(count > 20){ //I put this here mostly to stop infinite loops assuming this function wouldn't occur over 20 times.
return console.log("failed")
}
var endarray = [];
if(obj !== undefined && typeof(obj)==='object'){ //If the object isn't undefined and the object is an object...
for(var prop in obj){
console.log('"' + prop + '"');
endarray.push(stringifyJSON(prop) +'"' + ':' +'"'+ stringifyJSON(obj[prop])) //push the items into the array, using recursion.
}
if(typeof(obj) !== undefined){
return '{' + endarray.join() + '}'
}
}
};
//end result is "{undefined":"undefined,undefined":"undefined,undefined":"undefined,undefined":"{undefined":"undefined,undefined":"undefined},undefined":"{}}"
//JSON values cannot be a function, a date, or undefined
有人能指出我哪里出错了吗?通过递归,我在确定问题的根源时遇到了问题。
【问题讨论】:
-
通过递归,您试图累积某种结果。在这种情况下
endarray。但是您在递归的每次迭代中将其重置为一个空数组。您需要在递归函数之外声明endarray并建立您的结果,直到完成。 -
typeof(obj) !== undefined这将始终是true。不要使用typeof来检查undefined。这是一种短视且不必要的黑客行为,只会导致问题。 -
你可以定义
stringifyJSON接受两个参数,检查endarray是否定义,如果是,将值推送到数组,否则创建endarray。不过请注意,本机JSON.stringify()实现可以接受的不仅仅是一个对象或数组作为参数。 -
如果您确实使用 typeof,则需要将其与字符串进行比较。重写:
typeof obj !== 'undefined' -
另外,这比需要的更详细:
obj !== undefined && typeof(obj)==='object'。如果typeof obj是"object",那么您已经知道它不是undefined。也许你想避开null。
标签: javascript json recursion javascript-objects