因为JSON.stringify()在对象转json的时候会过滤掉function,那么我们就可以将function转成string并进行处理,满足要求constpage={version:"8.0.0.0",showCount:5,id:"newTab483617",name:"",a:function(){console.log(12321)}}//将对象转换为jsonconststr=JSON.stringify(page,function(key,val){if(typeofval==='function'){returnval+'';}returnval;})当console.log(str)json返回对象时,因为function是全部处理的转化为字符串,那么我们需要将字符串转化为函数,这里我们使用eval将字符串转化为函数constpage={version:"8.0.0.0",showCount:5,id:"newTab483617",name:"",a:function(){console.log(12321)}}//将对象转为jsonconststr=JSON.stringify(page,(key,val)=>{if(typeofval==='function'){returnval+'';}returnval;})console.log(str)//将json字符串转换为对象varjson=JSON.parse(str,(k,v)=>{if(v.indexOf&&v.indexOf('function')>-1){returneval("(function(){return"+v+"})()")}returnv;})console.log(json)json.a()//打印12321成功转回
