function jsonStringify(obj){
let type = typeof obj
if(type !== 'object' || obj == null){
if(['function', 'string', 'undefined'].includes(type)){
return '"' + obj + '"'
}
return String(obj)
}
else{
let json = []
let isArr = obj instanceof Array
for(let item in obj){
let t = obj[item]
let type = typeof t
if(['function', 'string', 'undefined'].includes(type)){
t = '"' + t + '"'
}
else if(type === 'object'){
t = jsonStringify(t)
}
json.push((isArr ? "": '"' + item + '":') + String(t))
}
return (isArr ? '[' : '{') + String(json) + (isArr ? ']' : '}')
}
}
jsonStringify({ x: 5 })
// "{"x":5}"
jsonStringify([1, "false", false])
// "[1,"false",false]"
jsonStringify({ b: undefined })
// "{"b":"undefined"}"
console.log(jsonStringify({ x: 5 }))
手写Json.stringify()
最新推荐文章于 2024-04-18 09:02:24 发布