面试题 - 手写JSON.stringify
一、JSON.stringify方法的基本使用
- 作用:将对象转换成JSON字符串的格式,配合JSON.parse可实现基础版的对象深拷贝
- 语法:JSON.stringify(value[, replacer [, space]])
let myObj1 = {
name:'Tim',
age:10,
friends:[1,2,3],
sex:'boy'
}
let objToString1 = JSON.stringify(myObj1);
console.log(objToString1);
let objToString2 = JSON.stringify(myObj1 , function (key,value){
if (typeof value === 'string') return undefined;
return value;
})
console.log(objToString2);
let objToString3 = JSON.stringify(myObj1,null,' ');
console.log(objToString3);
二、JSON.stringify对各种数据类型的处理
JSON.stringify | 输入类型 | 输出 |
---|
基本数据类型 | string | 字符串格式 |
| number | 字符串格式的数值 |
| boolean | “true”/“false” |
| null | “null” |
| undefined / symbol | “undefined” |
| NAN / ±Infinity | “null” |
引用数据类型(属性类型) | function | “undefined” |
| Date | Date的toJSON字符串 |
| RegExp | “{}” |
| 数组中出现了undefined、Symbol、Function | / |
| 普通的对象 | 1 - 如果对象有toJSON方法,则序列化toJSON方法的返回值 |
2 - 如果对象属性值为undefined,任意函数、Symbol,则忽略 | | |
3 - 如果以Symbol为属性键的属性都被忽略 | | |
三、手写JSON.stringify方法
function jsonStringify(data){
let type = typeof data;
if (type !== 'object'){
let result = data;
if (Number.isNaN(data) || data === Infinity){
return "null";
}
if (type === "function" || type === "undefined" || type === "symbol"){
return undefined;
}
if (type === "string"){
return `"${data}"`;
}
return data;
}else {
if (data === null){
return "null";
}
if (data.toJSON && typeof data.toJSON === 'function'){
return jsonStringify(data.toJSON())
}
if (data instanceof RegExp){
return "{}"
}
if (data instanceof Array){
let result = [];
data.forEach((item,index)=>{
if (typeof item === 'undefined' || typeof item === 'function' || typeof item === 'symbol') {
result[index] = "null";
} else {
result[index] = jsonStringify(item);
}
});
result = `[${result}]`;
return result.replace(/'/g,'"');
}
let result = [];
Object.keys(data).forEach((item,index) => {
if (typeof item !== 'symbol'){
if (data[item] !== undefined && typeof data[item] !== "function" && typeof data[item] !== 'symbol' ){
result.push(`"${item}":${jsonStringify(data[item])}`)
}
}
});
return `{${result}}`.replace(/'/g,'"');
}
}
let obj2 = {
name:'myName',
age:12,
hasMarried:false,
null:null,
undefined:undefined,
hobby:undefined,
getName(){
return this.name
},
date:new Date(),
RegExp:new RegExp("a"),
array1:[1,2,undefined,function (){},45],
obj3:{
name:'hello'
}
}
,"array1":[1,2,null,null,45],"obj3":{"name":"hello"}}
四、JSON.stringify总结
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ab3dbec1ccf349bcb361bba799c31b04.png)