1.函数
const fn = function(){}
const res = JSON.stringify(fn)
console.log(res) // undefined
函数会被转换为 undefined
2.数字
const num = 123
const res = JSON.stringify(num)
console.log(res) // "123"
数字会被转换为字符串
3.NaN
const res = JSON.stringify(NaN)
console.log(res) // "null"
NaN 会被转换为 "null"
4.布尔值
const b = true
const res = JSON.stringify(b)
console.log(res) // "true"
布尔值会被转换为字符串
5.补充
// undefined
JSON.stringify(undefined) // undefined
// null
JSON.stringify(null) // "null"
// 字符串
JSON.stringify("hello") // "\"hello\""
// 数组
JSON.stringify([1, "false", false]) // "[1,\"false\",false]"
// 对象
JSON.stringify({x: 5}) // "{\"x\":5}"
// 包含undefined的数组
JSON.stringify([undefined, 1]) // "[null,1]"
// 包含undefined的对象
JSON.stringify({a: undefined, b: 1}) // "{\"b\":1}"
总结
-
函数、undefined 会被转换为 undefined
-
NaN 和 null 会被转换为 "null"
-
数字和布尔值会被转换为对应的字符串
-
在数组中的 undefined 会被转换为 "null"
-
在对象中的 undefined 属性会被忽略