【问题标题】:Using recursion to create a JSON string (replicate stringify)使用递归创建 JSON 字符串(复制 stringify)
【发布时间】: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


【解决方案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)}


};

【讨论】:

  • 这是迄今为止最接近的答案,因为它返回了抛出的 testobj,但引号只是在答案中的错误位置。
  • 很高兴为您提供帮助。我确实注意到了报价问题,但您最初的问题询问了undefineds,所以这就是我关注的问题。希望您能够自己找出报价,但如果没有,请随时回信寻求更多帮助。 :)
猜你喜欢
  • 2015-07-31
  • 2014-07-22
  • 2022-01-09
  • 1970-01-01
  • 2016-02-10
  • 2015-03-10
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多