JS模拟 JSON.stringify 的基础功能实现
测试数据:
// 测试 stringify 函数(将对象转换为JSON格式的字符串) var obj = { a: 1, b: { c: 'hello', d: { e: [1,2,{x: 0}], f: function() {}, g: false, } }, h: null, j: undefined, m: new Map([[1, 2]]), };
模拟实现:
/** * 模拟 JSON.stringify */ var stringify = function (data) { const type = typeOf(data); let str = ''; switch (type) { case 'object': const keys = Object.keys(data); const size = keys.length; str += '{'; for (let i = 0; i < size; i++) { const key = keys[i]; const value = stringify(data[key]); if (value === undefined) continue; str += key + ':' + value; if (i < size - 1) str += ','; } str += '}'; return str; case 'array': const len = data.length; str += '['; for (let i = 0; i < len; i++) { const value = stringify(data[i]); if (value === undefined) continue; str += value; if (i < len - 1) str += ','; } str += ']'; return str; case 'string': return `"${data}"`; case 'number': return '' + data; case 'boolean': return data ? 'true' : 'false'; case 'null': return 'null'; case 'undefined': case 'function': case 'symbol': return; case 'map': case 'set': case 'weakmap': case 'weakset': case 'regexp': case 'arraybuffer': case 'blob': case 'int8array': case 'int16array': case 'int32array': return '{}'; case 'bigint': throw new TypeError('Do not know how to serialize a BigInt'); default: return; } }; /** * 判断获取数据的类型 */ var typeOf = function (o) { const toString = Object.prototype.toString; return toString.call(o).slice(8, -1).toLowerCase(); };
不足之处,请指正