当前位置: 首页 > Web前端 > HTML

JavaScriptJSON.stringify有趣的部分

时间:2023-03-28 15:31:51 HTML

参考语法JSON.stringify(value[,replacer[,space]])一般在使用JSON.stringify的时候,常见的有三种情况只是转换为字符串vararr=[{"name":"张三","age":99,"address":"武汉角角",fun:function(){console.log("我是评论")}}]varjsonstr=JSON.stringify(arr);console.log(jsonstr);这样简单方便,但是一点都不好看,所以我们可以继续改进,增加字符vararr=[{"name":"张三","age":99,"address":"武汉一角",fun:function(){console.log("我是评论")}}]varjsonstr=JSON.stringify(arr,null,"");console.log(jsonstr);中其实很简单,只需要在第三个参数中加一个空格即可,当然你也可以加\n或\t等特殊字符来过滤数据,修改replacer参数vararr=[{"name":"张三","age":99,"address":"武汉角角",fun:function(){console.log("我是评论")}}]varjsonstr=JSON.stringify(arr,[“年龄”],””);控制台日志(jsonstr);其实也能解决一个问题。JSON.stringify在转换字符串时默认不转换函数,可以传入第二个参数进行修改。其实如果要过滤数据,也可以在replacer方法中实现。当你返回一个对象或数组时,它会被序列化。所以判断是否返回value的类型就可以了functionreplacer(key,value){if(typeofvalue==="function"){returnString(value);}返回值;}vararr=[{"name":"张三","age":99,"address":"武汉一角",fun:function(){console.log("我是评论")}}]varjsonstr=JSON.stringify(arr,replacer,"");console.log(jsonstr);