【发布时间】:2017-07-29 23:51:20
【问题描述】:
我正在尝试复制 json stringify 方法,而是使用递归。我已经能够通过很多测试用例,但是当涉及到嵌套数组时,我似乎遇到了问题。如果数组('[]')中有任何空数组,我会得到类似 [,7,9] 而不是 [[],7,9] 的东西。另外,如果我通过:
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) {
var typecheck = typeof obj;
var resarray = stack;
if(resarray == null){ //does resarray exist? Is this the first time through?
var resarray = [];
}
if(typeof obj === "string"){ //Is obj a string?
return '"' + String(obj) + '"';
}
if((Array.isArray(obj)) && (obj.length > 0)){ //If not a string, is it an object?
for(var i = 0; i<obj.length;i++){
if(Array.isArray(obj[i])){
var arraytemp = []
stringifyJSON(arraytemp.push(obj[i]),resarray) // this is probably incorrect, this is how i handle a nested array situation
}
if(typeof obj[i] === 'number'){ //if the number is inside of the array, don't quote it
resarray.push(obj[i]);
}
else if(typecheck === 'object' && Array.isArray(obj[0])){
resarray.push('[' + obj[i] + ']');
}
else{
resarray.push('"' + obj[i] + '"');
}
obj.shift() //delete the first object in the array and get ready to recurse to get to the second object.
stringifyJSON(obj,resarray); //remember the new array when recursing by passing it into the next recursive instance
}
}
if(obj !== null && typeof obj === 'object'){ //is obj an object?
for(var key in obj){
stringifyJSON(resarray.push(key + '"' + ':' + obj[key]),resarray)
}
}
if(typeof obj === "number" || obj == null || obj === true || obj === false){ //special cases and if it's a number
return '' + obj + ''
}
if(typecheck === 'object'){ //a special case where you have an empty array that needs to be quoted.
return '['+resarray+']'
}
return '' + resarray.join('') + '';
};
//JSON values cannot be a function, a date, or undefined
【问题讨论】:
-
我还没有完成代码,但是调用递归函数时需要返回吗?例如
return stringifyJSON(...) -
这是一个尝试解决的有趣问题,但请确保它只是为了锻炼而不是您实际使用的东西——我在下面的回答中提供了许多细节。如果您有任何问题,我很乐意为您提供帮助。
标签: javascript arrays json recursion