如何在简化的JSON.stringify实现中解决每个循环错误?

时间:2016-01-14 00:58:19

标签: javascript loops recursion underscore.js details

我正在使用测试框架尝试返回{"foo":true,"bar":false,null},而是返回{"foo":true,"bar":false,"baz":null}。在各个点检查result的值之后,看起来虽然我的每个循环都是为所有对象元素调用的,但它并没有执行我尝试记录最终键或其(最终)周围标点符号的情况。但是,循环正在记录值及其后续逗号。

任何人都可以帮助发现特定的错误吗?

var stringifyJSON = function(val) {
  var result = '';
  //define basic return types
  var primitive = function(value) {
    if (typeof value === "number" || value === null || typeof value === 'boolean') {
      return value;
    } else if (typeof value === "string") {
      return '"' + value + '"';
      // func, undef., symb. null in array AND as primitive, ommit in obj
    } else if (typeof value !== 'object') {
      return 'null';
    }
  };

  //treat objects (and arrays)
  if (typeof val === "object" && val !== null) {
    val instanceof Array ? result += '[' : result += '{';
    _.each(val, function(el, key, col) {
      if (typeof el === "object") {
        //recurse if nested. start off new brackets.
        result += stringifyJSON(el);
        if (key !== val.length - 1) {
          result += ','; ///
        }
        //not nested (base case)
      } else {
        if (val instanceof Array) {
          result += primitive(el);
          if (key !== val.length - 1) {
            result += ',';
          }
        } else { /// objects
          result += '"' + key + '":' + primitive(val[key]) + ','; //this comma is being added but the first half is not.
          //console.log(result);
        }
      }
    });
    //outside loop: remove final comma from objects, add final brackets
    if (val instanceof Array) {
      result += ']'
    } else {
      if (result[result.length - 1] === ',') {
        //console.log(result);
        result = result.slice(0, -1);
        //console.log(result); 
      }
      result += '}';
    }

    //treat primitives
  } else {
    result += primitive(val);
  }
  //console.log(result);
  return result;

};

1 个答案:

答案 0 :(得分:3)

_.each循环中的第一个测试是错误的。如果你有一个嵌套在另一个对象中的对象,它将只输出嵌套对象,而不将键放在它之前。另一个问题是,如果val.length不是数组,则无法使用val。最后,当您显示数组或对象元素时,您需要递归,而不仅仅是使用primitive()

_.each(val, function(el, key, col) {
    if (val instanceof Array) {
      result += stringifyJSON(el);
      if (key !== val.length - 1) {
        result += ',';
      }
    } else { /// objects
      result += '"' + key + '":' + stringifyJSON(el) + ','; //this comma is being added but the first half is not.
      //console.log(result);
    }
  }
});