如何解决简化的JSON.stringify实现中的每个循环错误
How to solve each loop bug within simplified JSON.stringify implementation?
我正在使用测试框架来尝试返回{"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);
}
}
});
相关文章:
- 如何使用动画实现纸张推车
- 客户端服务器REST API captcha实现
- 如何实现此布局
- Meteor忘记了密码的实现
- 使用Native Sockets在Android中实现WebSockets
- 在样板文件中实现Ajax
- instanceof是如何在JavaScript中实现的
- 如何正确实现Jquery多选小部件
- 实现一个建立在google.com之上的自定义搜索引擎
- 多个组件是如何实现的
- window.location使用jquery mobile实现chrome跳转
- 如何在OpenERP中实现网络摄像头
- Node.js使用Series函数(模式?)实现流控制时出现意外结果
- javascript加密实现,包括可信否认
- 为什么JSON.stringify没有序列化原型值
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- 尝试JSON.stringify Ember模型时Id丢失
- 如何解决简化的JSON.stringify实现中的每个循环错误
- 注意到JSON.stringify的不同实现之间有一个奇怪的差异
- JSON.stringify的递归实现