<!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>