lgwebdream / FE-Interview

🔥🔥🔥 前端面试,独有前端面试题详解,前端面试刷题必备,1000+前端面试真题,Html、Css、JavaScript、Vue、React、Node、TypeScript、Webpack、算法、网络与安全、浏览器
https://lgwebdream.github.io/FE-Interview/
Other
6.82k stars 896 forks source link

请实现一个 JSON.stringfy #708

Open lgwebdream opened 4 years ago

lgwebdream commented 4 years ago

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

gaohan1994 commented 5 months ago

const jsonStringfy = source => {
  let result = "";
  const cache = new Map();

  const dp = data => {
    const values = [];
    Object.keys(data).forEach(key => {
      if (data[key] instanceof Object) {
        if (cache.has(data[key])) {
          values.push(`"${key}":${cache.get(data[key])}`);
        } else {
          const dataStr = dp(data[key]);
          cache.set(data[key], dataStr);
          values.push(`"${key}":${dataStr}`);
        }
      } else {
        values.push(`"${key}":"${data[key]}"`);
      }
    });

    return result + `{${values.join(",")}}`;
  };

  return dp(source);
};
image
Alicca-miao commented 4 days ago
 function myparse(source){

            let re=''
            let cache=new Map()
            let dp = (obj)=>{
                let values=[]
                for(let key in obj){

                    if(typeof obj[key]==='object') {
                        if(cache.get(obj[key])){
                            values.push(`"${key}":${cache.get(obj[key])}`)
                            //“”是json标准要求
                        }
                        else {
                            let datastr= dp(obj[key])
                            cache.set(obj[key],datastr)
                            values.push(`"${key}":${datastr}`)
                        }
                    } else values.push(`"${key}":${obj[key]}`)

                }
                re=`{${values.join(',')}}`
                return re

            }
            return dp(source)
        }

    // 测试示例
    const obj1 = { a: 1, b: { c: 2 }, d: null };
    const obj2 = { name: "Alice", age: 25, hobbies: ["reading", "gaming"] };
    const obj3 = { foo: { bar: { baz: 3 } }, qux: "hello" };
    const obj4 = { a: 1, b: 2, c: { d: 3, e: { f: 4 } } };

    console.log(myparse(obj1)); // 输出: {"a":"1","b":{"c":"2"},"d":null}
    console.log(myparse(obj2)); // 输出: {"name":"Alice","age":"25","hobbies":"reading,gaming"}
    console.log(myparse(obj3)); // 输出: {"foo":{"bar":{"baz":"3"}},"qux":"hello"}
    console.log(myparse(obj4)); // 输出: {"a":"1","b":"2","c":{"d":"3","e":{"f":"4"}}}