再帰を使用してJSON.stringify()を複製しようとしています。返されたJSON文字列でなぜ定義されていないのか分かりません。ここで私はこれまで何をやったかだ:私は間違って行くよどこ再帰を使用して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){
\t 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.
\t 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){
\t console.log('"' + prop + '"');
\t endarray.push(stringifyJSON(prop) +'"' + ':' +'"'+ stringifyJSON(obj[prop])) //push the items into the array, using recursion.
}
if(typeof(obj) !== undefined){
\t 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'を宣言し、完了するまで結果を構築する必要があります。 – rasmeister
'typeof(obj)!== undefined'これは常に' true'です。 'undefined 'をチェックするのに' typeof'を使わないでください。それは、問題を引き起こすだけである、近視眼的で不必要なハックです。 –
'stringifyJSON'を定義して2つのパラメータを受け入れることができます。' endarray'が定義されているかどうかを確認し、yesの場合は配列に値をプッシュし、そうでなければ 'endarray'を作成します。注意してくださいが、ネイティブの 'JSON.stringify()'実装では、オブジェクトまたは配列以上のものをパラメータとして受け入れることができます。 – guest271314