用原生的js实现JSON.stringify的函数
- User
用原生的js实现JSON.stringify的函数
Assistant
以下是一个用原生JavaScript实现的
JSON.stringify函数:function stringify(obj) { const type = typeof obj; if (type === 'undefined') { return 'undefined'; } else if (type === 'string') { return '"' + obj.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"'; } else if (type === 'number' || type === 'boolean') { return obj.toString(); } else if (type === 'object') { if (obj === null) { return 'null'; } else if (Array.isArray(obj)) { const arr = []; for (let i = 0; i < obj.length; i++) { arr.push(stringify(obj[i])); } return '[' + arr.join(',') + ']'; } else { const keys = Object.keys(obj); const arr = []; for (let i = 0; i < keys.length; i++) { const key = keys[i]; arr.push('"' + key.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '":' + stringify(obj[key])); } return '{' + arr.join(',') + '}'; } } else if (type === 'function') { return undefined; } } // 测试 const obj = { a: 1, b: 'hello', c: true, d: null, e: undefined, f: function() {}, g: [1, 2, 3], h: { i: 1, j: 2 } }; console.log(stringify(obj));
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.