实现一个JSON.stringify()


function jsonstringify(obj){
  let type = typeof obj;
  if(type !== 'object'){

    if(/string|undefined|function/.test(type)){

      obj = '"' + obj +'"'

    }

    return String(obj)

 

  }else{

    let arr = Array.isArray(obj);
    let json =[];

    for(let i in obj){

      let j = obj[i];

      let type = typeof j

      if(/string|undefined|function/.test(type)){

        j = '"' + j +'"'

      }else if(type == 'object'){

        j = jsonstringify(j)

      }

      json.push((arr ? "" : '"' + i + '":') + String(j));

    }

    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}")

  }
}

jsonstringify({x:1})  //"{"x":1}"

jsonstringify({x:undefined})  //"{"x":"undefined"}"

jsonstringify([false,'false','true',true,12])  //"[false,"false","true",true,12]"


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM