Javascript 如何解决简化JSON.stringify实现中的每个循环错误?
我正在使用一个测试框架来尝试返回Javascript 如何解决简化JSON.stringify实现中的每个循环错误?,javascript,loops,recursion,underscore.js,details,Javascript,Loops,Recursion,Underscore.js,Details,我正在使用一个测试框架来尝试返回{“foo”:true,“bar”:false,null},但是相反,我返回{“foo”:true,“bar”:false,“baz”:null}。在不同点检查result的值后,它看起来好像是在为所有对象元素调用我的each循环,但它既没有执行我记录最终键的尝试,也没有执行其(最终)周围标点符号的尝试。但是,循环正在记录值及其后面的逗号 有人能帮忙找出那个特定的bug吗 var stringifyJSON = function(val) { var resu
{“foo”:true,“bar”:false,null}
,但是相反,我返回{“foo”:true,“bar”:false,“baz”:null}
。在不同点检查result
的值后,它看起来好像是在为所有对象元素调用我的each循环,但它既没有执行我记录最终键的尝试,也没有执行其(最终)周围标点符号的尝试。但是,循环正在记录值及其后面的逗号
有人能帮忙找出那个特定的bug吗
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;
};
中的第一个测试。每个循环都是错误的。如果有一个对象嵌套在另一个对象中,它将只输出嵌套对象,而不将键放在它前面。另一个问题是,如果val
不是数组,则不能使用val.length
。最后,在显示数组或对象元素时,需要递归,而不仅仅是使用primitive()
你的第一句话毫无意义。您试图返回什么,返回的是什么?谢谢@Barmar,没有插入。为什么不使用JSON.stringify
?这是一项任务吗?@MuliYulzary,我正在指导自己学习javascript。其想法是构建JSON.stringify,而不仅仅是使用它。
_.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);
}
}
});