我試圖複製json stringify方法,而是使用遞歸。我已經能夠通過大量的測試用例,但是當涉及到嵌套數組時,我似乎遇到了問題。如果數組中有任何空數組('[]'),我會得到類似[,7,9]而不是[[],7,9]的東西。另外,如果我傳遞:使用Javascript的遞歸方法
stringifyJSON([[["test","mike",4,["jake"]],3,4]])
"[[test,mike,4,jake,3,4]]"
我以爲我是在得到這個工作接近,但我可能不得不重新開始。你們有什麼想法可以改變我爲嵌套的例子做這項工作嗎?下面的代碼我現在有:
var testarray = [9,[[],2,3]] //should return '[9,[[],2,3]]'
var count = 0
var stringifyJSON = function(obj,stack) {
\t var typecheck = typeof obj;
\t var resarray = stack;
\t if(resarray == null){ \t //does resarray exist? Is this the first time through?
\t \t var resarray = [];
\t }
\t if(typeof obj === "string"){ \t //Is obj a string?
\t \t return '"' + String(obj) + '"';
\t }
\t if((Array.isArray(obj)) && (obj.length > 0)){ //If not a string, is it an object?
\t \t for(var i = 0; i<obj.length;i++){
\t \t \t if(Array.isArray(obj[i])){
\t \t \t \t var arraytemp = []
\t \t \t \t stringifyJSON(arraytemp.push(obj[i]),resarray) // this is probably incorrect, this is how i handle a nested array situation
\t \t \t }
\t \t \t if(typeof obj[i] === 'number'){ \t \t //if the number is inside of the array, don't quote it
\t \t \t \t resarray.push(obj[i]);
\t \t \t }
\t \t \t else if(typecheck === 'object' && Array.isArray(obj[0])){
\t \t \t \t resarray.push('[' + obj[i] + ']');
\t \t \t }
\t \t \t else{
\t \t \t \t resarray.push('"' + obj[i] + '"');
\t \t \t }
\t \t \t
\t \t \t obj.shift() \t \t //delete the first object in the array and get ready to recurse to get to the second object.
\t \t \t stringifyJSON(obj,resarray); //remember the new array when recursing by passing it into the next recursive instance
\t \t }
\t }
\t if(obj !== null && typeof obj === 'object'){ \t //is obj an object?
\t \t for(var key in obj){
\t \t \t stringifyJSON(resarray.push(key + '"' + ':' + obj[key]),resarray)
\t \t }
\t \t
\t }
\t if(typeof obj === "number" || obj == null || obj === true || obj === false){ \t //special cases and if it's a number
\t \t return '' + obj + ''
\t }
\t if(typecheck === 'object'){ \t //a special case where you have an empty array that needs to be quoted.
\t \t return '['+resarray+']'
\t }
\t return '' + resarray.join('') + '';
\t
};
//JSON values cannot be a function, a date, or undefined
我沒有通過代碼了,但woudlnt」你的變化 -
我們可以很容易這樣的功能添加到我們的代碼以上調用遞歸函數時需要返回?例如'return stringifyJSON(...)' – derp
這是一個有趣的問題嘗試和解決,但要確保它只是爲了鍛鍊而不是實際使用的東西 - 我在下面的答案中提供了許多細節。如果您有任何問題,我很樂意提供幫助。 – naomik