简易版本JSON.stringify的实现及其六大特性详解
2022-04-14 21:18:05 来源:易采站长站 作者:
目录
前言jsON.stringify六大特性特性一特性二特性三
特性四
特性五
特性六
手动实现stringify总结
前言
JSON.stringify是一个使用非常高频的API,但是其却存在一个特性,我们在使用的过程中需要留意这些特性以避免为代码程序埋雷,那么接下来便一起动手实现一个简易版本的jsonStringify函数
JSON.stringify六大特性
特性一
布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值
现在有这么一个对象:
const obj = { bol: new Boolean(true), num: new Number(1), str: new String(1)}利用typeof检测obj各个属性的数据类型
typeof obj.bol; // objecttypeof obj.num; // objecttypeof obj.str; // object
将其序列化stringify之后
JSON.stringify(obj); // {"bol":true,"num":1,"str":"1"}此时再将其解析parse进行各个属性的数据类型
const stringifyObj = JSON.parse(JSON.stringify(obj));typeof stringifyObj.bol; // booleantypeof stringifyObj.num; // numbertypeof stringifyObj.str; // string
特性二
NaN、Infinity、-Infinity以及null在序列化stringify时都会被当作null
const obj = { nan: NaN, infinity: Infinity, nul if (isUndefined(item) || isSymbol(item) || isFunction(item)) { result[index] = "null"; } else { result[index] = jsonStringify(item); } }); result = "[" + result + "]"; return result.replace(/'/g, '"'); } else if (isObject(data)) { // 处理普通对象 let result = []; Object.keys(data).forEach((item, index) => { if (typeof item !== "symbol") { //key 如果是 symbol 对象,忽略 if ( data[item] !== undefined && typeof data[item] !== "function" && typeof data[item] !== "symbol" ) { //键值如果是 undefined、function、symbol 为属性值,忽略 result.push( '"' + item + '"' + ":" + jsonStringify(data[item]) ); } } }); return ("{" + result + "}").replace(/'/g, '"'); } else if (type !== "object") { let result = data; //data 可能是基础数据类型的情况在这里处理 if (Number.isNaN(data) || data === Infinity) { //NaN 和 Infinity 序列化返回 "null" result = "null"; } else if (isUndefined(data) || isSymbol(data) || isFunction(data)) { // 由于 function 序列化返回 undefined,因此和 undefined、symbol 一起处理 return undefined; } else if (type === "string") { result = '"' + data + '"'; } return String(result); }}至此简易版本的JSON.stringify完成,虽然能力尚欠缺许多,主要是提供一个思路,核心注释已注释在代码中,可结合代码和上文的特性一起理解
总结
暂时禁止评论













闽公网安备 35020302000061号