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

How to solve each loop bug within simplified JSON.stringify implementation?

本文关键字:实现 stringify 错误 循环 JSON 解决 何解决      更新时间:2023-09-26

我正在使用测试框架来尝试返回{"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;
};

_.each循环中的第一个测试是错误的。如果你有一个对象嵌套在另一个对象中,它只会输出嵌套的对象,而不把键放在它前面。另一个问题是,如果val不是数组,则不能使用val.length。最后,当你显示数组或对象元素时,你需要递归,而不仅仅是使用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);
    }
  }
});