我试图使用递归来复制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

有人可以指出我哪里出错吗?通过递归,我在确定问题根源时遇到了问题。
答案 0 :(得分:1)
要获得正确的解决方案,还需要做几件事。
首先,您没有递归的基本情况,因此在每个递归跟踪的基本级别,不返回任何内容(即,隐式返回undefined)。首先,您必须添加一个基本情况,其中整数,字符串,布尔值和其他基本类型将转换为字符串。
其次,你必须在递归调用之前检查obj !== null
,因为typeof(null)
评估为“对象”,奇怪的是。
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 && obj !== null && 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() + '}'
}
}
if (obj !== undefined) {return String(obj)}
};