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