我正在尝试编写一个接受一些对象的函数,例如一个数字、一个字符串、一个列表或一个映射(键值对);并将该输入的有效 JSON 表示形式作为字符串返回。
我已经为简单的数字和字符串输入设置了其他 json 编码器:
Input => Output
a number with value 123 => 123 (string)
a string with value abc => "abc" (string)
但我在转换数组时遇到问题,例如 [1,"2",3]
Input => Output
1,2,three array => [1,2,"three"] (string)
这是我当前的代码:
var my_json_encode = function(input) {
if(typeof(input) === "string"){
return '"'+input+'"'
}
if(typeof(input) === "number"){
return `${input}`
}
//This is causing my issue
if(Array.isArray(input)) {
console.log(input)
}
我可以简单地添加并返回 JSON.stringify(input) 来更改它,但我不想使用它。我知道我可以创建某种递归解决方案,因为我为数字和字符串设置了基本案例。我被阻止了,任何帮助将不胜感激
编辑:所以答案部分提供了下面的解决方案!谢谢 :)
慕容708150
蛊毒传说
30秒到达战场
随时随地看视频慕课网APP
相关分类