JavaScript toString、String和stringify方法区别


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>JavaScript toString与String方法区别</title>
    </head>
    <body>
        <script type="text/javascript">
            //一 toString限制
            // 报错Cannot read property 'toString' of undefined
            // console.log(undefined.toString())
            // 报错Cannot read property 'toString' of undefined
            //console.log(null.toString())

            //二 String无限制
 console.log(String(undefined)) console.log(String(null)) //三 toString可根据进制编码
 let num = 10; console.log(num.toString(2)) </script>
    </body>
</html>

 二、stringify也可以实现字符串化,并且健壮性也良好

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>JavaScript toString、String和stringify方法区别</title>
    </head>
    <body>
        <script type="text/javascript"> let a = { age: undefined, name: null } //输出 {"name":null}
 console.log(JSON.stringify(a)) let b; //输出 undefined
 console.log(JSON.stringify(b)); let c = null; //输出 null
 console.log(JSON.stringify(c)) </script>
    </body>
</html>

 


免责声明!

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



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